{"id":13561497,"url":"https://github.com/StructureBuilder/react-keep-alive","last_synced_at":"2025-04-03T17:31:02.338Z","repository":{"id":34307351,"uuid":"173570867","full_name":"StructureBuilder/react-keep-alive","owner":"StructureBuilder","description":"A component that maintains component state and avoids repeated re-rendering.","archived":false,"fork":false,"pushed_at":"2023-01-03T17:13:58.000Z","size":1000,"stargazers_count":995,"open_issues_count":75,"forks_count":107,"subscribers_count":12,"default_branch":"master","last_synced_at":"2025-03-17T16:06:37.406Z","etag":null,"topics":[],"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/StructureBuilder.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.MIT","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-03-03T12:19:19.000Z","updated_at":"2025-03-13T06:59:55.000Z","dependencies_parsed_at":"2023-01-15T06:12:53.606Z","dependency_job_id":null,"html_url":"https://github.com/StructureBuilder/react-keep-alive","commit_stats":null,"previous_names":[],"tags_count":29,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StructureBuilder%2Freact-keep-alive","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StructureBuilder%2Freact-keep-alive/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StructureBuilder%2Freact-keep-alive/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StructureBuilder%2Freact-keep-alive/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/StructureBuilder","download_url":"https://codeload.github.com/StructureBuilder/react-keep-alive/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247046832,"owners_count":20874731,"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":[],"created_at":"2024-08-01T13:00:57.573Z","updated_at":"2025-04-03T17:30:57.327Z","avatar_url":"https://github.com/StructureBuilder.png","language":"TypeScript","readme":"\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://github.com/Sam618/react-keep-alive\"\u003e\n    \u003cimg width=\"120\" src=\"https://github.com/Sam618/react-keep-alive/raw/master/assets/react-logo.png\"\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n\u003ch1 align=\"center\"\u003eReact Keep Alive\u003c/h1\u003e\n\u003cdiv align=\"center\"\u003e\n\n[![npm](https://img.shields.io/npm/v/react-keep-alive.svg?style=for-the-badge)](https://www.npmjs.com/package/react-keep-alive) [![Travis (.org)](https://img.shields.io/travis/Sam618/react-keep-alive.svg?style=for-the-badge)](https://travis-ci.org/Sam618/react-keep-alive.svg?branch=master) [![LICENSE](https://img.shields.io/npm/l/react-keep-alive.svg?style=for-the-badge)](https://github.com/Sam618/react-keep-alive/blob/master/LICENSE.MIT) [![npm bundle size (minified + gzip)](https://img.shields.io/bundlephobia/minzip/react-keep-alive.svg?style=for-the-badge)](https://www.npmjs.com/package/react-keep-alive) [![downloads](https://img.shields.io/npm/dm/react-keep-alive.svg?style=for-the-badge)](https://www.npmjs.com/package/react-keep-alive) [![typescript](https://img.shields.io/badge/language-typescript-blue.svg?style=for-the-badge)](https://www.typescriptlang.org/)\n\n  \u003cp\u003e\u003ca href=\"https://nodei.co/npm/react-keep-alive/\"\u003e\u003cimg src=\"https://nodei.co/npm/react-keep-alive.png?downloads=true\u0026downloadRank=true\u0026stars=true\"\u003e\u003c/a\u003e\u003c/p\u003e\n\n  \u003cp\u003eA component that maintains component state and avoids repeated re-rendering.\u003c/p\u003e\n\n  \u003cdiv style=\"width: 100px; text-align: left;\"\u003e\n    \u003cdiv\u003eEnglish | \u003ca href=\"https://github.com/Sam618/react-keep-alive/blob/master/README.zh-CN.md\"\u003e中文\u003c/a\u003e\u003c/div\u003e\n    \u003cdiv\u003e\u003ca href=\"https://github.com/Sam618/react-keep-alive/blob/master/ONLINE_EDITOR.md\"\u003eOnline Editor\u003c/a\u003e\u003c/div\u003e\n  \u003c/div\u003e\n\u003c/div\u003e\n\n\n## ✨ Features\n- Not based on React Router, so you can use it wherever you need to cache it.\n- You can easily use \u003cKeepAlive\u003e to wrap your components to keep them alive.\n- Because it is not controlled by `display: none | block`, you can use animation.\n- You will be able to use the latest React Hooks.\n- Ability to manually control whether your components need to stay active.\n\n## 📦 Installation\nReact Keep Alive requires React 16.3 or later, but if you use React Hooks, you must be React 16.8 or higher.\n\nTo use React Keep Alive with your React app:\n\n```bash\nnpm install --save react-keep-alive\n```\n\n\n## 🔨 Usage\nReact Keep Alive provides `\u003cProvider\u003e`, you must use `\u003cProvider\u003e` to wrap the `\u003cKeepAlive\u003e` cache to take effect.\n\n```JavaScript\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport {\n  Provider,\n  KeepAlive,\n} from 'react-keep-alive';\nimport Test from './views/Test';\n\nReactDOM.render(\n  \u003cProvider\u003e\n    \u003cKeepAlive name=\"Test\"\u003e\n      \u003cTest /\u003e\n    \u003c/KeepAlive\u003e\n  \u003c/Provider\u003e,\n  document.getElementById('root'),\n);\n```\n\n\n## 💡 Why do you need this component?\nIf you've used [Vue](https://vuejs.org/), you know that it has a very good component ([keep-alive](https://vuejs.org/v2/guide/components-dynamic-async.html)) that keeps the state of the component to avoid repeated re-rendering.\n\nSometimes, we want the list page to cache the page state after the list page enters the detail page. When the detail page returns to the list page, the list page is still the same as before the switch.\n\nOh, this is actually quite difficult to achieve, because the components in React cannot be reused once they are uninstalled. Two solutions are proposed in [issue #12039](https://github.com/facebook/react/issues/12039). By using the style switch component display (`display: none | block;`), this can cause problems, such as when you switch components, you can't use animations; or use data flow management tools like Mobx and Redux, but this is too much trouble.\n\nIn the end, I implemented this effect through the [React.createPortal API](https://reactjs.org/docs/portals.html). `react-keep-alive` has two main components `\u003cProvider\u003e` and `\u003cKeepAlive\u003e`. The `\u003cProvider\u003e` is responsible for saving the component's cache and rendering the cached component outside of the application via the React.createPortal API before processing. The cached components must be placed in `\u003cKeepAlive\u003e`, and `\u003cKeepAlive\u003e` will mount the components that are cached outside the application to the location that really needs to be displayed.\n\n\n## 📝 API Reference\n\n### `Provider`\nSince the cached components need to be stored, the `\u003cProvider\u003e` must be rendered at the top of the application for the program to run properly.\n\n#### Props\n`include`: Only components that match key will be cached. It can be a string, an array of strings, or a regular expression, eg:\n```JavaScript\n\u003cProvider include=\"A,B\"\u003e...\u003c/Provider\u003e\n// or\n\u003cProvider include={['A', 'B']}\u003e...\u003c/Provider\u003e\n// or\n\u003cProvider include={/A|B/}\u003e...\u003c/Provider\u003e\n```\n\n`exclude`: Any component that matches key will not be cached. It can be a string, an array of strings, or a regular expression.\n\n`max`(`v2.5.2+`): If the maximum value is set, the value in the cache is deleted after it goes out.\n\n#### Example\nIn the example below, the \u003cApp /\u003e component is our root-level component. This means it’s at the very top of our component hierarchy.\n\n```javascript\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Provider } from 'react-keep-alive';\nimport App from './App';\n\nReactDOM.render(\n  \u003cProvider\u003e\n    \u003cApp /\u003e\n  \u003c/Provider\u003e,\n  document.getElementById('root'),\n);\n```\n\n##### Usage with React Router and Mobx React\n\n```JavaScript\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport {\n  BrowserRouter as Router,\n} from 'react-router-dom';\nimport {\n  Provider as MobxProvider,\n} from 'mobx-react';\nimport {\n  Provider as KeepAliveProvider,\n} from 'react-keep-alive';\n\nReactDOM.render(\n  \u003cMobxProvider\u003e\n    \u003cRouter\u003e\n      \u003cKeepAliveProvider\u003e\n        \u003cApp /\u003e\n      \u003c/KeepAliveProvider\u003e\n    \u003c/Router\u003e\n  \u003c/MobxProvider\u003e,\n  document.getElementById('root'),\n);\n```\n\n**Note**: You must put \u003cProvider\u003e in \u003cRouter\u003e and the React Router must be sure to be the **latest version**. Because React Keep Alive uses the **new Context**, you must ensure that the Router does the same. Please use the following command to install the latest version.\n\n```bash\nnpm install react-router@next react-router-dom@next\n```\n\n\n### `KeepAlive`\nChildren of `\u003cKeepAlive\u003e` will be cached, but we have to make sure that `\u003cKeepAlive\u003e` is inside `\u003cProvider\u003e`.\n\n#### Props\n`name`: Name must exist and need to ensure that all `\u003cKeepAlive\u003e` names under the current `\u003cProvider\u003e` are unique(1.2.0 added, Replace key).\n\n`disabled`: When we don't need components for caching, we can disable it; the disabled configuration will only takes effect when the component's status changes from unactive to active.\n\n`extra`(`v2.0.1+`): Additional data can be obtained through `bindLifecycle`.\n\n**Note**: `\u003cKeepAlive\u003e` The innermost outer layer of the packaged component must have a real DOM tag.\n\n#### Example\n```JavaScript\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport {\n  BrowserRouter as Router,\n  Switch,\n  Route,\n  Link,\n} from 'react-router-dom';\nimport {\n  Provider,\n  KeepAlive,\n} from 'react-keep-alive';\n\nclass One extends React.Component {\n  render() {\n    return (\n      // a real DOM tag\n      \u003cdiv\u003eThis is One.\u003c/div\u003e\n    );\n  }\n}\n\nclass App extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cSwitch\u003e\n          \u003cRoute path=\"/one\"\u003e\n            \u003cKeepAlive name=\"One\"\u003e\n              \u003cOne /\u003e\n            \u003c/KeepAlive\u003e\n          \u003c/Route\u003e\n        \u003c/Switch\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n\nReactDOM.render(\n  \u003cRouter\u003e\n    \u003cProvider\u003e\n      \u003cApp /\u003e\n    \u003c/Provider\u003e\n  \u003c/Router\u003e,\n  document.getElementById('root'),\n);\n```\n\n##### Usage with `include` props of `\u003cProvider\u003e`\n```JavaScript\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport {\n  BrowserRouter as Router,\n  Switch,\n  Route,\n  Link,\n} from 'react-router-dom';\nimport {\n  Provider,\n  KeepAlive,\n} from 'react-keep-alive';\n\nclass One extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003eThis is One.\u003c/div\u003e\n    );\n  }\n}\n\nclass App extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cSwitch\u003e\n          \u003cRoute path=\"/one\"\u003e\n            \u003cKeepAlive name=\"One\"\u003e\n              \u003cOne /\u003e\n            \u003c/KeepAlive\u003e\n          \u003c/Route\u003e\n        \u003c/Switch\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n\nReactDOM.render(\n  \u003cRouter\u003e\n    \u003cProvider include=\"One\"\u003e\n      \u003cApp /\u003e\n    \u003c/Provider\u003e\n  \u003c/Router\u003e,\n  document.getElementById('root'),\n);\n```\n\n**Note**: If you want to use the **lifecycle**, wrap the components in a `bindLifecycle` high-level component.\n\n### `bindLifecycle`\nComponents that pass this high-level component wrap will have the **correct** lifecycle, and we have added two additional lifecycles, `componentDidActivate` and `componentWillUnactivate`.\n\nLifecycle after adding:\n![Lifecycle after adding](https://github.com/Sam618/react-keep-alive/raw/master/assets/lifecycle.png)\n\n`componentDidActivate` will be executed once after the initial mount or from the unactivated state to the active state. although we see `componentDidActivate` after `componentDidUpdate` in the `Updating` phase, this does not mean `componentDidActivate` Always triggered.\n\nAt the same time, only one of the lifecycles of `componentWillUnactivate` and `componentWillUnmount` is triggered. `componentWillUnactivate` is executed when caching is required; `componentWillUnmount` is executed without caching.\n\n#### Example\n```JavaScript\nimport React from 'react';\nimport {bindLifecycle} from 'react-keep-alive';\n\n@bindLifecycle\nclass Test extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        This is Test.\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n\n### `useKeepAliveEffect`\n`useKeepAliveEffect` will fire when the component enters and leaves; because the component will not be unmounted while it is still active, so if you use `useEffect`, that will not achieve the real purpose.\n\n**Note**: `useKeepAliveEffect` uses the latest React Hooks, so you must make sure React is the latest version.\n\n#### Example\n```JavaScript\nimport React from 'react';\nimport {useKeepAliveEffect} from 'react-keep-alive';\n\nfunction Test() {\n  useKeepAliveEffect(() =\u003e {\n    console.log(\"mounted\");\n    return () =\u003e {\n      console.log(\"unmounted\");\n    };\n  });\n  return (\n    \u003cdiv\u003e\n      This is Test.\n    \u003c/div\u003e\n  );\n}\n```\n\n\n## 🐛 Issues\nIf you find a bug, please file an issue on [our issue tracker on GitHub](https://github.com/Sam618/react-keep-alive/issues).\n\n\n## 🏁 Changelog\nChanges are tracked in the [CHANGELOG.md](https://github.com/Sam618/react-keep-alive/blob/master/CHANGELOG.md).\n\n\n## 📄 License\nReact Keep Alive is available under the [MIT](https://github.com/Sam618/react-keep-alive/blob/master/LICENSE) License.\n","funding_links":[],"categories":["TypeScript","目录"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FStructureBuilder%2Freact-keep-alive","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FStructureBuilder%2Freact-keep-alive","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FStructureBuilder%2Freact-keep-alive/lists"}