{"name":"react-activation","version":"0.13.3","keywords":["multiple tabs","React Keep Alive","Keep Alive","keep-alive","KeepAlive","activation","react cache","react tabs cache","react router cache","vue keep-alive"],"author":{"name":"CJY0208"},"license":"ISC","_id":"react-activation@0.13.3","maintainers":[{"name":"cjy0208","email":"375564567@qq.com"}],"homepage":"https://github.com/CJY0208/react-activation","dist":{"shasum":"0a1882adc35f3a30a29a1eb67f5e322145fb899d","tarball":"http://registry-npm.ywwl.com/react-activation/download/react-activation-0.13.3.tgz","fileCount":12,"integrity":"sha512-ydKP2yEzPIrMJnT+1DbGQGJ1+oL65ARyjpdPwIsQ8JYMn36GocLT0RLh6ty89o5cQrznYUSDPLnce/n8fQAlsQ==","signatures":[{"sig":"MEUCIQDEuDzJXM+jQFxokO5P2wcc3qQVo2Q4pewYCgxA3eui7AIgdrKygajQyHp9BLlzkSsuFemgo/gvhY1+W3hiGhmr37g=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":255909,"size":65624,"noattachment":false,"key":"/react-activation/-/react-activation-0.13.3.tgz"},"main":"index.js","scripts":{"build":"rollup --config","format":"prettier --write \"./src/**/*.js\"","manual:publish":"npm run build && np --no-cleanup --yolo --no-publish && npm publish"},"_npmUser":{"name":"cjy0208","email":"375564567@qq.com"},"repository":{"url":"git+https://github.com/CJY0208/react-activation.git","type":"git"},"description":"<KeepAlive /> for React like <keep-alive /> in vue","directories":{},"licenseText":"MIT License\n\nCopyright (c) 2023 CJY\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","sideEffects":false,"dependencies":{"szfe-tools":"npm:@fexd/tools@^0.1.6","react-node-key":"^0.4.0","hoist-non-react-statics":"^3.3.0"},"_hasShrinkwrap":false,"devDependencies":{"np":"^6.2.5","rollup":"^1.11.3","prettier":"^2.2.1","@babel/core":"^7.5.5","@babel/preset-env":"^7.5.5","@babel/preset-react":"^7.0.0","babel-plugin-import":"^1.13.3","rollup-plugin-babel":"^4.3.2","rollup-plugin-uglify":"^6.0.2","rollup-plugin-node-resolve":"^4.2.3","@babel/plugin-proposal-class-properties":"^7.5.5"},"peerDependencies":{"react":">=16"},"_npmOperationalInternal":{"tmp":"tmp/react-activation_0.13.3_1747792600415_0.45632309215911593","host":"s3://npm-registry-packages-npm-production"},"readme":"# ⚠️ NOTICE\n\n- DO NOT use `<React.StrictMode />`\n- (React v18+) DO NOT use `ReactDOMClient.createRoot`, use `ReactDOM.render` instead, https://github.com/CJY0208/react-activation/issues/225#issuecomment-1311136388\n\n   or You can disable `autoFreeze` to work with `createRoot` though this may result in performance loss\n\n  ```jsx\n  import { KeepAlive } from 'react-activation'\n  KeepAlive.defautProps.autoFreeze = false // default 'true'\n  ```\n\n# React Activation\n\n[![size](https://img.shields.io/bundlephobia/minzip/react-activation@latest.svg)](https://bundlephobia.com/result?p=react-activation@latest)\n[![dm](https://img.shields.io/npm/dm/react-activation.svg)](https://github.com/CJY0208/react-activation)\n![](https://komarev.com/ghpvc/?username=cjy0208-react-activation&label=VIEWS)\n\nEnglish | [中文说明](./README_CN.md)\n\n**HACK Implementation** of the `<keep-alive />` function in `Vue` For `React`\n\nPlease also pay attention to official support [`<Offscreen />`](https://github.com/reactwg/react-18/discussions/19) in `React 18.x`\n\n---\n\nMore stable `<KeepAlive />` function with `babel` pre-compilation\n\n[Online Demo](https://codesandbox.io/s/affectionate-beaver-solkt)\n\n<img src=\"./docs/basicReactActivation.gif\">\n\n---\n\n## More examples\n\n- [Closable tabs with `react-router`](https://codesandbox.io/s/keguanbideyifangwenluyou-tab-shilikeanluyoucanshufenduofenhuancun-ewycx)\n- [Closable tabs with `umi`](https://codesandbox.io/s/umi-keep-alive-tabs-demo-knfxy)\n- [Using Animation with `react-router`](https://codesandbox.io/s/luyouzhuanchangdonghuashili-jdhq1)\n\n---\n\n## Compatibility\n\n- React v16 / v17 / v18\n\n- Preact v10+\n\n- Compatible with SSR\n\n---\n\n## Install\n\n```bash\nyarn add react-activation\n# or\nnpm install react-activation\n```\n\n---\n\n## Usage\n\n#### 1. (Optional, Recommended) Add `react-activation/babel` plugins in `.babelrc`\n\n[Why is it needed?](https://github.com/CJY0208/react-activation/issues/18#issuecomment-564360695)\n\nThe plugin adds a `_nk` attribute to each JSX element during compilation to help the `react-activation` runtime **generate an unique identifier by render location** base on [`react-node-key`](https://github.com/CJY0208/react-node-key).\n\n```javascript\n{\n  \"plugins\": [\n    \"react-activation/babel\"\n  ]\n}\n```\n\n**(0.11.0+)** If you don't want to use Babel, it is recommended that each `<KeepAlive>` declare a globally unique and invariant `cacheKey` attribute to ensure the stability of the cache, as follows:\n\n```jsx\n<KeepAlive cacheKey=\"UNIQUE_ID\" />\n```\n\n#### 2. Wrap the components that need to keep states with `<KeepAlive>`\n\nLike the `<Counter>` component in the example\n\n```javascript\n// App.js\n\nimport React, { useState } from 'react'\nimport KeepAlive from 'react-activation'\n\nfunction Counter() {\n  const [count, setCount] = useState(0)\n\n  return (\n    <div>\n      <p>count: {count}</p>\n      <button onClick={() => setCount(count => count + 1)}>Add</button>\n    </div>\n  )\n}\n\nfunction App() {\n  const [show, setShow] = useState(true)\n\n  return (\n    <div>\n      <button onClick={() => setShow(show => !show)}>Toggle</button>\n      {show && (\n        <KeepAlive>\n          <Counter />\n        </KeepAlive>\n      )}\n    </div>\n  )\n}\n\nexport default App\n```\n\n#### 3. Place the `<AliveScope>` outer layer at a location that will not be unmounted, usually at the application entrance\n\nNote: When used with `react-router` or `react-redux`, you need to place `<AliveScope>` inside `<Router>` or `<Provider>`\n\n```javascript\n// index.js\n\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport { AliveScope } from 'react-activation'\n\nimport App from './App'\n\nReactDOM.render(\n  <AliveScope>\n    <App />\n  </AliveScope>,\n  document.getElementById('root')\n)\n```\n\n---\n\n## Lifecycle\n\n`ClassComponent` works with `withActivation` decorator\n\nUse `componentDidActivate` and `componentWillUnactivate` to correspond to the two states of \"activate\" and \"unactivate\" respectively.\n\n`FunctionComponent` uses the `useActivate` and `useUnactivate` hooks respectively\n\n```javascript\n...\nimport KeepAlive, { useActivate, useUnactivate, withActivation } from 'react-activation'\n\n@withActivation\nclass TestClass extends Component {\n  ...\n  componentDidActivate() {\n    console.log('TestClass: componentDidActivate')\n  }\n\n  componentWillUnactivate() {\n    console.log('TestClass: componentWillUnactivate')\n  }\n  ...\n}\n...\nfunction TestFunction() {\n  useActivate(() => {\n    console.log('TestFunction: didActivate')\n  })\n\n  useUnactivate(() => {\n    console.log('TestFunction: willUnactivate')\n  })\n  ...\n}\n...\nfunction App() {\n  ...\n  return (\n    {show && (\n      <KeepAlive>\n        <TestClass />\n        <TestFunction />\n      </KeepAlive>\n    )}\n  )\n}\n...\n```\n\n---\n\n## Cache Control\n\n### Manually control the cache\n\n1. Add the `name` attribute to the `<KeepAlive>` tag that needs to control the cache.\n\n2. Get control functions using `withAliveScope` or `useAliveController`.\n\n   - **drop(name)**: (`drop` can only be used for nodes in the cache state. If the node is not cached but needs to clear the cache state, please use `refresh`)\n\n     Unload the `<KeepAlive>` node in cache state by name. The name can be of type `String` or `RegExp`. Note that only the first layer of content that hits `<KeepAlive>` is unloaded and will not be uninstalled in `<KeepAlive>`. Would not unload nested `<KeepAlive>`.\n\n   - **dropScope(name)**: (`dropScope` can only be used for nodes in the cache state. If the node is not cached but needs to clear the cache state, please use `refreshScope`)\n\n     Unloads the `<KeepAlive>` node in cache state by name. The name optional type is `String` or `RegExp`, which will unload all content of `<KeepAlive>`, including all `<KeepAlive>` nested in `<KeepAlive>`.\n\n   - **refresh(name)**:\n\n     Refresh the `<KeepAlive>` node in cache state by name. The name can be of type `String` or `RegExp`. Note that only the first layer of content that hits `<KeepAlive>` is refreshed and will not be uninstalled in `<KeepAlive>`. Would not refresh nested `<KeepAlive>`.\n\n   - **refreshScope(name)**:\n\n     Refresh the `<KeepAlive>` node in cache state by name. The name optional type is `String` or `RegExp`, which will refresh all content of `<KeepAlive>`, including all `<KeepAlive>` nested in `<KeepAlive>`.\n\n\n   - **clear()**:\n\n     will clear all `<KeepAlive>` in the cache\n\n   - **getCachingNodes()**:\n\n     Get all the nodes in the cache\n\n```javascript\n...\nimport KeepAlive, { withAliveScope, useAliveController } from 'react-activation'\n...\n<KeepAlive name=\"Test\">\n  ...\n    <KeepAlive>\n      ...\n        <KeepAlive>\n          ...\n        </KeepAlive>\n      ...\n    </KeepAlive>\n  ...\n</KeepAlive>\n...\nfunction App() {\n  const { drop, dropScope, clear, getCachingNodes } = useAliveController()\n\n  useEffect(() => {\n    drop('Test')\n    // or\n    drop(/Test/)\n    // or\n    dropScope('Test')\n\n    clear()\n  })\n\n  return (\n    ...\n  )\n}\n// or\n@withAliveScope\nclass App extends Component {\n  render() {\n    const { drop, dropScope, clear, getCachingNodes } = this.props\n\n    return (\n      ...\n    )\n  }\n}\n...\n```\n\n---\n\n### Automatic control cache\n\nAdd the `when` attribute to the `<KeepAlive />` tag that needs to control the cache. The value is as follows\n\n#### When the `when` type is `Boolean`\n\n- **true**: Cache after uninstallation\n- **false**: Not cached after uninstallation\n\n```javascript\n<KeepAlive when={false}>\n```\n\n#### When the `when` type is `Array`\n\nThe **1th** parameter indicates whether it needs to be cached at the time of uninstallation.\n\nThe **2th** parameter indicates whether to unload all cache contents of `<KeepAlive>`, including all `<KeepAlive>` nested in `<KeepAlive>`.\n\n```javascript\n// For example:\n// The following indicates that it is not cached when uninstalling\n// And uninstalls all nested `<KeepAlive>`\n<KeepAlive when={[false, true]}>\n  ...\n  <KeepAlive>\n    ...\n    <KeepAlive>...</KeepAlive>\n    ...\n  </KeepAlive>\n  ...\n</KeepAlive>\n```\n\n#### When the `when` type is `Function` (**Recommended**)\n\nThe return value is the above `Boolean` or `Array`, which takes effect as described above.\n\nThe final calculation time of `when` is adjusted to `componentWillUnmount` lifecicle of `<KeepAlive>`, the problem that most of the `when` do not achieve the expected effect can be avoided.\n\n```jsx\n<KeepAlive when={() => true}>\n<KeepAlive when={() => [false, true]}>\n```\n\n---\n\n## Multiple Cache\n\nUnder the same parent node, `<KeepAlive>` in the same location will use the same cache by default.\n\nFor example, with the following parameter routing scenario, the `/item` route will be rendered differently by `id`, but only the same cache can be kept.\n\n```javascript\n<Route\n  path=\"/item/:id\"\n  render={props => (\n    <KeepAlive>\n      <Item {...props} />\n    </KeepAlive>\n  )}\n/>\n```\n\nSimilar scenarios, you can use the `id` attribute of `<KeepAlive>` to implement multiple caches according to specific conditions.\n\n```javascript\n<Route\n  path=\"/item/:id\"\n  render={props => (\n    <KeepAlive id={props.match.params.id}>\n      <Item {...props} />\n    </KeepAlive>\n  )}\n/>\n```\n\n---\n\n## Save Scroll Position (`true` by default)\n\n`<KeepAlive />` would try to detect scrollable nodes in its `children`, then, save their scroll position automaticlly before `componentWillUnactivate` and restore saving position after `componentDidActivate`\n\nIf you don't want `<KeepAlive />` to do this thing, set `saveScrollPosition` prop to `false`\n\n```javascript\n<KeepAlive saveScrollPosition={false} />\n```\n\nIf your components share screen scroll container, `document.body` or `document.documentElement`, set `saveScrollPosition` prop to `\"screen\"` can save sharing screen container's scroll position before `componentWillUnactivate`\n\n```javascript\n<KeepAlive saveScrollPosition=\"screen\" />\n```\n\n---\n\n## Principle\n\nPass the `children` attribute of `<KeepAlive />` to `<AliveScope />` and render it with `<Keeper />`\n\nAfter rendering `<Keeper />`, the content is transferred to `<KeepAlive />` through `DOM` operation.\n\nSince `<Keeper />` will not be uninstalled, caching can be implemented.\n\n[Simplest Implementation Demo](https://codesandbox.io/s/zuijian-react-keepalive-shixian-ovh90)\n\n<img src=\"./docs/reactActivationPrinciple.gif\">\n\n---\n\n## Breaking Change\n\n1. `<KeepAlive />` needs to pass children to `<AliveScope />` , so the rendering of the real content will be **slower than the normal situation**\n\n   Will have a certain impact on the function of strictly relying on the lifecycle order, such as getting the value of `ref` in `componentDidMount`, as follows\n\n   ```javascript\n   class Test extends Component {\n     componentDidMount() {\n       console.log(this.outside) // will log <div /> instance\n       console.log(this.inside) // will log undefined\n     }\n\n     render() {\n       return (\n         <div>\n           <div\n             ref={ref => {\n               this.outside = ref\n             }}\n           >\n             Outside KeepAlive\n           </div>\n           <KeepAlive>\n             <div\n               ref={ref => {\n                 this.inside = ref\n               }}\n             >\n               Inside KeepAlive\n             </div>\n           </KeepAlive>\n         </div>\n       )\n     }\n   }\n   ```\n\n   The above error in `ClassComponent` can be fixed by using the `withActivation` high-level component\n\n   `FunctionComponent` currently has no processing method, you can use `setTimeout` or `nextTick` to delay ref getting behavior\n\n   ```javascript\n   @withActivation\n   class Test extends Component {\n     componentDidMount() {\n       console.log(this.outside) // will log <div /> instance\n       console.log(this.inside) // will log <div /> instance\n     }\n\n     render() {\n       return (\n         <div>\n           <div\n             ref={ref => {\n               this.outside = ref\n             }}\n           >\n             Outside KeepAlive\n           </div>\n           <KeepAlive>\n             <div\n               ref={ref => {\n                 this.inside = ref\n               }}\n             >\n               Inside KeepAlive\n             </div>\n           </KeepAlive>\n         </div>\n       )\n     }\n   }\n   ```\n\n2. Destructive impact on `Context`\n\n   after `react-actication@0.8.0` with `react@16.3+`, this question has been automatic fixed\n\n   `react-actication@0.8.0` with `react@17+` you Need to make the following changes to achieve automatic repair\n\n   ```jsx\n   import { autoFixContext } from 'react-activation'\n\n   autoFixContext(\n    [require('react/jsx-runtime'), 'jsx', 'jsxs', 'jsxDEV'],\n    [require('react/jsx-dev-runtime'), 'jsx', 'jsxs', 'jsxDEV']\n   )\n   ```\n   \n   Versions below `react-actication@0.8.0` need to be repaired manually, refer to the following\n\n   Problem reference: https://github.com/StructureBuilder/react-keep-alive/issues/36\n\n   ```javascript\n   <Provider value={1}>\n     {show && (\n       <KeepAlive>\n         <Consumer>\n           {(\n             context // Since the rendering level is broken, the context cannot be obtained here.\n           ) => <Test contextValue={context} />}\n         </Consumer>\n       </KeepAlive>\n     )}\n     <button onClick={toggle}>toggle</button>\n   </Provider>\n   ```\n\n   Choose a repair method\n\n   - Create `Context` using `createContext` exported from `react-activation`\n\n   - Fix the affected `Context` with `fixContext` exported from `react-activation`\n\n   ```javascript\n   ...\n   import { createContext } from 'react-activation'\n\n   const { Provider, Consumer } = createContext()\n   ...\n   // or\n   ...\n   import { createContext } from 'react'\n   import { fixContext } from 'react-activation'\n\n   const Context = createContext()\n   const { Provider, Consumer } = Context\n\n   fixContext(Context)\n   ...\n   ```\n\n3. Affects the functionality that depends on the level of the React component, as follows\n\n   - [x] [Fix `withRouter/hooks` of react-router](https://github.com/CJY0208/react-activation/issues/77)\n   - [x] ~~Error Boundaries~~ (Fixed)\n   - [x] ~~React.Suspense & React.lazy~~ (Fixed)\n   - [ ] React Synthetic Event Bubbling Failure\n   - [ ] Other undiscovered features\n\n---\n","publish_time":1747792600618,"_cnpm_publish_time":1747792600618,"dist-tags":{"beta":"0.8.0-beta.1","latest":"0.13.4"}}