{"id":19556670,"url":"https://github.com/irychen/keepalive-for-react","last_synced_at":"2025-04-08T10:14:29.243Z","repository":{"id":198825525,"uuid":"701444962","full_name":"irychen/keepalive-for-react","owner":"irychen","description":"React KeepAlive is a component that can cache the state of the component and reuse it when needed.","archived":false,"fork":false,"pushed_at":"2024-10-24T11:03:07.000Z","size":5538,"stargazers_count":174,"open_issues_count":0,"forks_count":33,"subscribers_count":6,"default_branch":"main","last_synced_at":"2024-10-24T16:36:45.203Z","etag":null,"topics":["keepalive","react","react-keepalive"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","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/irychen.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-10-06T16:39:47.000Z","updated_at":"2024-10-24T11:03:11.000Z","dependencies_parsed_at":"2023-12-15T02:47:03.505Z","dependency_job_id":"71a9413d-bc6b-4cf5-acd4-603b06ee3fb4","html_url":"https://github.com/irychen/keepalive-for-react","commit_stats":null,"previous_names":["irychen/react-keepalive"],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/irychen%2Fkeepalive-for-react","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/irychen%2Fkeepalive-for-react/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/irychen%2Fkeepalive-for-react/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/irychen%2Fkeepalive-for-react/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/irychen","download_url":"https://codeload.github.com/irychen/keepalive-for-react/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247683327,"owners_count":20978850,"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":["keepalive","react","react-keepalive"],"created_at":"2024-11-11T04:38:49.925Z","updated_at":"2025-04-08T10:14:29.212Z","avatar_url":"https://github.com/irychen.png","language":"TypeScript","readme":"\u003cp align=\"center\"\u003e\n  \u003cimg width=\"120\" src=\"./react-keepalive.png\" alt=\"keepalive-for-react logo\"\u003e\n\u003c/p\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \u003ch1 align=\"center\"\u003e\n    KeepAlive for React\n  \u003c/h1\u003e\n\u003c/div\u003e\n\n\u003cp align=\"center\"\u003eA React KeepAlive component like keep-alive in vue\u003c/p\u003e\n\n[中文](./README.zh_CN.md) | English\n\n[![NPM version](https://img.shields.io/npm/v/keepalive-for-react.svg?style=flat)](https://npmjs.com/package/keepalive-for-react) [![NPM downloads](https://img.shields.io/npm/dm/keepalive-for-react.svg?style=flat)](https://npmjs.com/package/keepalive-for-react)\n\n## Packages\n\n| Package                                         | Version                                                                                                                                        | Description                  |\n| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |\n| [keepalive-for-react](./packages/core)          | [![NPM version](https://img.shields.io/npm/v/keepalive-for-react.svg?style=flat)](https://npmjs.com/package/keepalive-for-react)               | Core keepalive functionality |\n| [keepalive-for-react-router](./packages/router) | [![NPM version](https://img.shields.io/npm/v/keepalive-for-react-router.svg?style=flat)](https://npmjs.com/package/keepalive-for-react-router) | React Router integration     |\n\n## Features\n\n-   Support react-router-dom v6+ or react-router v7+\n-   Support React v16+ ~ v18+\n-   Support Suspense and Lazy import\n-   Support ErrorBoundary\n-   Support Custom Container\n-   Support Switching Animation Transition with className `active` and `inactive`\n-   Simply implement, without any extra dependencies and hacking ways\n-   Only 6KB minified size\n\n## Attention\n\n-   DO NOT use \u003cReact.StrictMode /\u003e, it CANNOT work with keepalive-for-react in development mode. because it can lead to\n    some unexpected behavior.\n\n-   In Router only support react-router-dom v6+\n\n## Install\n\n```bash\nnpm install keepalive-for-react\n```\n\n```bash\nyarn add keepalive-for-react\n```\n\n```bash\npnpm add keepalive-for-react\n```\n\n## Usage\n\n### in react-router-dom v6+ or react-router v7+\n\n1. install react-router-dom v6+ or react-router v7+\n\n```bash\n# v6+\nnpm install react-router-dom keepalive-for-react keepalive-for-react-router@1.x.x\n# v7+\nnpm install react-router keepalive-for-react keepalive-for-react-router@2.x.x\n```\n\n2. use KeepAlive in your project\n\n```tsx\n// v6+ keepalive-for-react-router@1.x.x\n// v7+ keepalive-for-react-router@2.x.x\nimport KeepAliveRouteOutlet from \"keepalive-for-react-router\";\n\nfunction Layout() {\n    return (\n        \u003cdiv className=\"layout\"\u003e\n            \u003cKeepAliveRouteOutlet /\u003e\n        \u003c/div\u003e\n    );\n}\n```\n\nor\n\n```tsx\nimport { useMemo } from \"react\";\n// v6+\nimport { useLocation, useOutlet } from \"react-router-dom\";\n// v7\n// import { useLocation, useOutlet } from \"react-router\";\nimport { KeepAlive, useKeepAliveRef } from \"keepalive-for-react\";\n\nfunction Layout() {\n    const location = useLocation();\n    const aliveRef = useKeepAliveRef();\n\n    const outlet = useOutlet();\n\n    // determine which route component to is active\n    const currentCacheKey = useMemo(() =\u003e {\n        return location.pathname + location.search;\n    }, [location.pathname, location.search]);\n\n    return (\n        \u003cdiv className=\"layout\"\u003e\n            \u003cMemoizedScrollTop\u003e\n                \u003cKeepAlive transition aliveRef={aliveRef} activeCacheKey={currentCacheKey} max={18}\u003e\n                    \u003cSuspense fallback={\u003cLoadingArea /\u003e}\u003e\n                        \u003cSpreadArea\u003e{outlet}\u003c/SpreadArea\u003e\n                    \u003c/Suspense\u003e\n                \u003c/KeepAlive\u003e\n            \u003c/MemoizedScrollTop\u003e\n        \u003c/div\u003e\n    );\n}\n```\n\ndetails see [examples/react-router-dom-simple-starter](./examples/react-router-dom-simple-starter)\n\n[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/irychen/keepalive-for-react/tree/main/examples/react-router-dom-simple-starter)\n\n### in simple tabs\n\n```bash\nnpm install keepalive-for-react\n```\n\n```tsx\nconst tabs = [\n    {\n        key: \"tab1\",\n        label: \"Tab 1\",\n        component: Tab1,\n    },\n    {\n        key: \"tab2\",\n        label: \"Tab 2\",\n        component: Tab2,\n    },\n    {\n        key: \"tab3\",\n        label: \"Tab 3\",\n        component: Tab3,\n    },\n];\n\nfunction App() {\n    const [currentTab, setCurrentTab] = useState\u003cstring\u003e(\"tab1\");\n\n    const tab = useMemo(() =\u003e {\n        return tabs.find(tab =\u003e tab.key === currentTab);\n    }, [currentTab]);\n\n    return (\n        \u003cdiv\u003e\n            {/* ... */}\n            \u003cKeepAlive transition={true} activeCacheKey={currentTab} exclude={[\"tab3\"]}\u003e\n                {tab \u0026\u0026 \u003ctab.component /\u003e}\n            \u003c/KeepAlive\u003e\n        \u003c/div\u003e\n    );\n}\n```\n\ndetails see [examples/simple-tabs-starter](./examples/simple-tabs-starter)\n\n[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/irychen/keepalive-for-react/tree/main/examples/simple-tabs-starter)\n\n## KeepAlive Props\n\ntype definition\n\n```tsx\ninterface KeepAliveProps {\n    // determine which component to is active\n    activeCacheKey: string;\n    children?: KeepAliveChildren;\n    /**\n     * max cache count default 10\n     */\n    max?: number;\n    exclude?: Array\u003cstring | RegExp\u003e | string | RegExp;\n    include?: Array\u003cstring | RegExp\u003e | string | RegExp;\n    onBeforeActive?: (activeCacheKey: string) =\u003e void;\n    customContainerRef?: RefObject\u003cHTMLDivElement\u003e;\n    cacheNodeClassName?: string;\n    containerClassName?: string;\n    errorElement?: ComponentType\u003c{\n        children: ReactNode;\n    }\u003e;\n    /**\n     * transition default false\n     */\n    transition?: boolean;\n    /**\n     * use view transition to animate the component when switching tabs\n     * @see https://developer.chrome.com/docs/web-platform/view-transitions/\n     */\n    viewTransition?: boolean;\n    /**\n     * transition duration default 200\n     */\n    duration?: number;\n    aliveRef?: RefObject\u003cKeepAliveRef | undefined\u003e;\n    /**\n     * max alive time for cache node (second)\n     * @default 0 (no limit)\n     */\n    maxAliveTime?: number | MaxAliveConfig[];\n}\n\ninterface MaxAliveConfig {\n    match: string | RegExp;\n    expire: number;\n}\n```\n\n## Hooks\n\n### useEffectOnActive\n\n```tsx\nuseEffectOnActive(() =\u003e {\n    console.log(\"active\");\n}, []);\n```\n\n### useLayoutEffectOnActive\n\n```tsx\nuseLayoutEffectOnActive(\n    () =\u003e {\n        console.log(\"active\");\n    },\n    [],\n    false,\n);\n// the third parameter is optional, default is false,\n// if true, which means the callback will be skipped when the useLayoutEffect is triggered in first render\n```\n\n### useKeepAliveContext\n\ntype definition\n\n```ts\ninterface KeepAliveContext {\n    /**\n     * whether the component is active\n     */\n    active: boolean;\n    /**\n     * refresh the component\n     * @param {string} [cacheKey] - The cache key of the component. If not provided, the current cached component will be refreshed.\n     */\n    refresh: (cacheKey?: string) =\u003e void;\n    /**\n     * destroy the component\n     * @param {string} [cacheKey] - the cache key of the component, if not provided, current active cached component will be destroyed\n     */\n    destroy: (cacheKey?: string | string[]) =\u003e Promise\u003cvoid\u003e;\n    /**\n     * destroy all components\n     */\n    destroyAll: () =\u003e Promise\u003cvoid\u003e;\n    /**\n     * destroy other components except the provided cacheKey\n     * @param {string} [cacheKey] - The cache key of the component. If not provided, destroy all components except the current active cached component.\n     */\n    destroyOther: (cacheKey?: string) =\u003e Promise\u003cvoid\u003e;\n    /**\n     * get the cache nodes\n     */\n    getCacheNodes: () =\u003e Array\u003cCacheNode\u003e;\n}\n```\n\n```tsx\nconst { active, refresh, destroy, getCacheNodes } = useKeepAliveContext();\n// active is a boolean, true is active, false is inactive\n// refresh is a function, you can call it to refresh the component\n// destroy is a function, you can call it to destroy the component\n// ...\n// getCacheNodes is a function, you can call it to get the cache nodes\n```\n\n### useKeepAliveRef\n\ntype definition\n\n```ts\ninterface KeepAliveRef {\n    refresh: (cacheKey?: string) =\u003e void;\n    destroy: (cacheKey?: string | string[]) =\u003e Promise\u003cvoid\u003e;\n    destroyAll: () =\u003e Promise\u003cvoid\u003e;\n    destroyOther: (cacheKey?: string) =\u003e Promise\u003cvoid\u003e;\n    getCacheNodes: () =\u003e Array\u003cCacheNode\u003e;\n}\n```\n\n```tsx\nfunction App() {\n    const aliveRef = useKeepAliveRef();\n    // aliveRef.current is a KeepAliveRef object\n\n    // you can call refresh and destroy on aliveRef.current\n    aliveRef.current?.refresh();\n    // it is not necessary to call destroy manually, KeepAlive will handle it automatically\n    aliveRef.current?.destroy();\n\n    return \u003cKeepAlive aliveRef={aliveRef}\u003e{/* ... */}\u003c/KeepAlive\u003e;\n}\n// or\nfunction AppRouter() {\n    const aliveRef = useKeepAliveRef();\n    // aliveRef.current is a KeepAliveRef object\n\n    // you can call refresh and destroy on aliveRef.current\n    aliveRef.current?.refresh();\n    aliveRef.current?.destroy();\n    return \u003cKeepAliveRouteOutlet aliveRef={aliveRef} /\u003e;\n}\n```\n\n## Development\n\ninstall dependencies\n\n```bash\npnpm install\n```\n\nbuild package\n\n```bash\npnpm build\n```\n\nlink package to global\n\n```bash\npnpm link --global\n```\n\ntest in demo project\n\n```bash\ncd demo\npnpm link --global keepalive-for-react\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Firychen%2Fkeepalive-for-react","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Firychen%2Fkeepalive-for-react","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Firychen%2Fkeepalive-for-react/lists"}