{"id":13492371,"url":"https://github.com/shenjunru/react-fiber-keep-alive","last_synced_at":"2025-03-28T10:32:00.890Z","repository":{"id":41302223,"uuid":"498007246","full_name":"shenjunru/react-fiber-keep-alive","owner":"shenjunru","description":"A component that maintains component state and avoids repeated re-rendering.","archived":false,"fork":false,"pushed_at":"2022-07-01T05:31:07.000Z","size":256,"stargazers_count":65,"open_issues_count":4,"forks_count":1,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-03-07T18:47:06.826Z","etag":null,"topics":["keep-alive","react","react-dom","react-fiber"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/shenjunru.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-05-30T15:52:03.000Z","updated_at":"2024-12-30T09:21:33.000Z","dependencies_parsed_at":"2022-07-15T15:17:11.473Z","dependency_job_id":null,"html_url":"https://github.com/shenjunru/react-fiber-keep-alive","commit_stats":null,"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shenjunru%2Freact-fiber-keep-alive","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shenjunru%2Freact-fiber-keep-alive/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shenjunru%2Freact-fiber-keep-alive/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shenjunru%2Freact-fiber-keep-alive/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/shenjunru","download_url":"https://codeload.github.com/shenjunru/react-fiber-keep-alive/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246012538,"owners_count":20709464,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["keep-alive","react","react-dom","react-fiber"],"created_at":"2024-07-31T19:01:05.417Z","updated_at":"2025-03-28T10:32:00.280Z","avatar_url":"https://github.com/shenjunru.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# Keep-Alive for `React DOM`\n\n[![npm](https://img.shields.io/npm/v/react-fiber-keep-alive.svg?style=for-the-badge)](http://npm.im/react-fiber-keep-alive)\n[![downloads](https://img.shields.io/npm/dm/react-fiber-keep-alive.svg?style=for-the-badge)](https://www.npmjs.com/package/react-fiber-keep-alive)\n[![typescript](https://img.shields.io/badge/language-typescript-blue?style=for-the-badge)](https://www.typescriptlang.org/)\n[![LICENSE](https://img.shields.io/npm/l/react-fiber-keep-alive.svg?style=for-the-badge)](https://github.com/shenjunru/react-fiber-keep-alive/blob/main/LICENSE)\n\n`\u003cKeepAlive\u003e` is a component that maintains component state and avoids repeated re-rendering.\n\n\n## ✨ Features\n- [x] Only based on `React Fiber` and `React Hooks`.\n- [x] Triggers original class component life circle.\n- [x] Triggers original effect hooks.\n- [x] Supports context updates.\n- [x] Supports multiple `keep-alive`.\n- [x] Supports `react-dom` v16.8+.\n- [x] Supports `react-dom` v17.\n- [x] Supports `react-dom` v18.\n\n\n## 📦 Installation\n\n```bash\nnpm install --save react-fiber-keep-alive\n```\n\n\n## 🔨 Usage\n\n```JavaScript\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport KeepAlive from 'react-fiber-keep-alive';\n\nconst root = document.getElementById('root');\n\nReactDOM.render((\n    \u003cKeepAlive.Provider value={root}\u003e\n        ...\n        \u003cKeepAlive name=\"test\"\u003e\n            \u003cYourComponent /\u003e\n        \u003c/KeepAlive\u003e\n        ...\n    \u003c/KeepAlive.Provider\u003e\n), root);\n```\n\n## 📝 API\n\n- Provide `root` container element.\n    ```JSX\n    \u003cKeepAlive.Provider value={container}\u003e\n    ```\n  - Must be the root container of `render()`.\n  - If not provided, `keep-alive` will be disabled.\n\n- Wrap your component with `\u003cKeepAlive\u003e`\n    ```JSX\n    \u003cKeepAlive name=\"unique-key\"\u003e\n        \u003cYourComponent /\u003e\n    \u003c/KeepAlive\u003e\n    ```\n    - prop \"name\" is a required unique string used to identify the cache.\n    - prop \"ignore\" is a optional boolean used to bypass and clear the cache. (since 0.5.0)\n    - prop \"onRead(name: string): void\" is a optional callback after cache applied. (since 0.7.0)\n    - prop \"onSave(name: string): void\" is a optional callback after cache saved. (since 0.7.0)\n\n- Wrap your component with `keepLive()`.\n    ```JavaScript\n    import { keepAlive } from 'react-fiber-keep-alive';\n\n    const NewComponent = keepAlive(YourComponent, (props) =\u003e {\n        // props: the income props for `\u003cYourComponent\u003e`\n        \n        // you can use react hooks here\n\n        return `unique-key`;\n\n        // or\n\n        return {\n            name: `unique-key`,\n            // other props for `\u003cKeepAlive\u003e`\n        };\n    });\n    ```\n\n- Hook: `useIgnoreKeepAlive()` returns a cache cleaner function.\n    ```JavaScript\n    import { useIgnoreKeepAlive } from 'react-fiber-keep-alive';\n    \n    const ignoreCache = useIgnoreKeepAlive();\n\n    ignoreCache(`unique-key`);\n    ```\n\n- If the `render()` of class component has side effects.\n    ```JavaScript\n    import { markClassComponentHasSideEffectRender } from 'react-fiber-keep-alive';\n\n    markClassComponentHasSideEffectRender(ClassComponent);\n\n    // Example:\n    class Test extends React.Component {\n        render() {\n            // side effect here, ex: emit event here.\n            return null;\n        }\n    }\n    markClassComponentHasSideEffectRender(Test);\n    ```\n\n- If no need to trigger the effect hook while remounting.\n    ```JavaScript\n    import { markEffectHookIsOnetime } from 'react-fiber-keep-alive';\n\n    markEffectHookIsOnetime(effectHook);\n\n    // Example:\n    React.useEffect(markEffectHookIsOnetime(() =\u003e {\n        // do something\n    }), []);\n    React.useLayoutEffect(markEffectHookIsOnetime(() =\u003e {\n        // do something\n    }), []);\n    ```\n\n- `KeepAlive.Context` (since 0.7.0)\n    ```TSX\n    import * as React from 'react';\n    import KeepAlive, { Context, KeepAliveCache } from 'react-fiber-keep-alive';\n    import LRUCache from 'lru-cache';\n\n    /// Example: Use LRU to manage the cache\n    const YourKeepAliveProvider: React.FC\u003c{\n        children: React.ReactNode;\n        value: null | HTMLElement;\n    }\u003e = (props) =\u003e {\n        const container = props.value;\n        const context: Context = React.useMemo(() =\u003e {\n            if (!container) {\n                return [];\n            }\n            const caches = new LRUCache\u003cstring, KeepAliveCache\u003e({ \n                max: 10,\n            });\n            return [container, caches, new Map()];\n        }, []);\n\n        return (\n            \u003cKeepAlive.Context.Provider value={context}\u003e\n                {props.children}\n            \u003c/KeepAlive.Context.Provider\u003e\n        );\n    };\n    ```\n\n\n## 💡 Tips\n\n- Be careful the global side effects. (ex: insert global style)\n- Do not use `\u003cKeepAlive\u003e` under the `\u003cReact.StrictMode\u003e`.\n- Recursive `\u003cKeepAlive\u003e` handled by top level `\u003cKeepAlive\u003e`.\n- If the `container` changed in `ReactDOM.createPortal(children, container)`.\n  - All saved sub tree state will be lost.\n- Errors from `react-devtools` after `\u003cKeepAlive\u003e` remounted.\n  - Try force refresh the components tree. (ex: updates components filter)\n\n\n## 🏁 Tested\n\n### Examples\n- [react-router v5](https://codesandbox.io/s/keep-alive-react-router-example-hfbbi7)\n\n### React v16.8+ / v17 / v18\n- [x] `render(children, container)`\n- [x] `hydrate(children, container)`\n\n### React v18 (concurrent mode)\n- [x] `createRoot(container).render(children)`\n- [x] `hydrateRoot(container, children)`\n\n### Class Component\n- [x] `Component.getDerivedStateFromProps()`\n- [x] `Component.getDerivedStateFromError()`\n- [x] `instance.componentDidMount()`\n- [x] `instance.getSnapshotBeforeUpdate()`\n- [x] `instance.componentDidUpdate()`\n- [x] `instance.componentWillUnmount()`\n- [x] `instance.render()`\n\n### Function Component\n- [x] `useContext()`\n- [x] `useCallback()`\n- [x] `useEffect()`\n- [x] `useImperativeHandle()`\n- [x] `useLayoutEffect()`\n- [x] `useMemo()`\n- [x] `useRef()`\n- [x] `useState()`\n- [ ] `useDebugValue()`\n- [ ] `useDeferredValue()` (since v18)\n- [ ] `useId()` (since v18)\n- [x] `useInsertionEffect()` (since v18)\n- [ ] `useSyncExternalStore()` (since v18)\n- [ ] `useTransition()` (since v18)\n\n### Other\n- [x] `ReactDOM.createPortal(children, container)`\n- [x] `React.memo()`\n- [x] `React.forwardRef()`\n- [x] `React.lazy()`\n- [x] `\u003cSuspense\u003e`\n- [ ] `\u003cOffscreen\u003e` (since v18)\n\n\n## 🐛 Issues\n\nIf you find a bug, please file an issue on [our issue tracker on GitHub](https://github.com/shenjunru/react-fiber-keep-alive/issues).\n\n\n## 📄 License\n\nCopyright © 2022 [**Shen Junru**](https://github.com/shenjunru) • [**MIT license**](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshenjunru%2Freact-fiber-keep-alive","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshenjunru%2Freact-fiber-keep-alive","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshenjunru%2Freact-fiber-keep-alive/lists"}