{"name":"use-context-selector","description":"React useContextSelector hook in userland","version":"1.3.2","author":{"name":"Daishi Kato"},"repository":{"type":"git","url":"git+https://github.com/dai-shi/use-context-selector.git"},"source":"./src/index.ts","main":"./dist/index.umd.js","module":"./dist/index.modern.js","react-native":"./dist/index.native.modern.js","types":"./dist/src/index.d.ts","sideEffects":false,"scripts":{"compile":"run-s compile:*","compile:dom":"microbundle build -f modern,umd","precompile:native":"mkdir src/native && cp src/index.ts src/native/index.ts && cp src/batchedUpdates.native.ts src/native/batchedUpdates.ts","compile:native":"microbundle build -f modern,umd -i ./src/native/index.ts -o ./dist/index.native.js","postcompile:native":"rm -r src/native","test":"run-s eslint tsc-test jest","eslint":"eslint --ext .js,.ts,.tsx --ignore-pattern dist .","jest":"jest --preset ts-jest/presets/js-with-ts __tests__/*.tsx","tsc-test":"tsc --project . --noEmit","apidoc":"documentation readme --section API --markdown-toc false --parse-extension ts src/*.ts","examples:01_minimal":"DIR=01_minimal EXT=js webpack-dev-server","examples:02_typescript":"DIR=02_typescript webpack-dev-server"},"keywords":["react","context","hooks"],"license":"MIT","dependencies":{},"devDependencies":{"@testing-library/react":"^11.2.2","@types/jest":"^26.0.15","@types/react":"^17.0.0","@types/react-dom":"^17.0.0","@types/scheduler":"^0.16.1","@typescript-eslint/eslint-plugin":"^4.9.0","@typescript-eslint/parser":"^4.9.0","documentation":"^13.1.0","eslint":"^7.14.0","eslint-config-airbnb":"^18.2.1","eslint-plugin-import":"^2.22.1","eslint-plugin-jsx-a11y":"^6.4.1","eslint-plugin-react":"^7.21.5","eslint-plugin-react-hooks":"^4.2.0","html-webpack-plugin":"^4.5.0","jest":"^26.6.3","microbundle":"^0.12.4","npm-run-all":"^4.1.5","react":"^17.0.1","react-dom":"^17.0.1","scheduler":"^0.19.1","ts-jest":"^26.4.4","ts-loader":"^8.0.11","typescript":"^4.1.2","webpack":"^4.44.2","webpack-cli":"^3.3.12","webpack-dev-server":"^3.11.0"},"peerDependencies":{"react":">=16.8.0","react-dom":"*","react-native":"*","scheduler":">=0.19.0"},"peerDependenciesMeta":{"react-dom":{"optional":true},"react-native":{"optional":true}},"gitHead":"aa5c2d7fe33343c38073969227825f1cb119ccbe","bugs":{"url":"https://github.com/dai-shi/use-context-selector/issues"},"homepage":"https://github.com/dai-shi/use-context-selector#readme","_id":"use-context-selector@1.3.2","_nodeVersion":"12.20.0","_npmVersion":"6.14.8","dist":{"integrity":"sha512-XRRlZD8+FIac3RtmOEqq8SizNEQI6oldteuOWu+F+pDooiJPPaFgw+8wckX+/fuJ80DRJB9HP99UdIq8A1YSMA==","shasum":"326a76875be2914c2d5cabf63349cbd9fda09d34","tarball":"http://registry-npm.ywwl.com/use-context-selector/download/use-context-selector-1.3.2.tgz","fileCount":17,"unpackedSize":76413,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfyL3HCRA9TVsSAnZWagAA8L4P/29Fgi2LtYYkfoiiuXUO\nxadpfz1NQ/QzefCCgCUVaMJx5l+7gfaODEPImhExGu1j6na41pOeNFhHvwbZ\nG2Wt30aUiUL1U8/Gd7wqKdeJWUFTAN4K1jEbqIqF00sUj8+U7iDI6mQsNZkB\n0m5F6GWvuRz6vwwsjkYC2N7el3k5JxVeVUET7lMZsfJHYMjYBY05zuA7NB4m\n8jqAb37RPTC7oL7ojrWxOKqZvkiFO82oiuVyP6GZefPOTkKKyiA8jyZyUiXC\nrjBPay9J8fAsKHG3q9jFOO4Z+7VOFY2ib265neqZ19de2L3mFDkLiR/lZ5on\nasmzc4iNVefw6afyExQzNwBuebwUQqP36a6LgqVrYB/XxCwFlCidaSG2bz5C\nA68R3WRTTFcRuduXnh18wbgRZFZPa1S7/Eef96QL0Mxrj1vww7pfoUP8MjXw\nbeWxDgjC4MyF6XsLXaa8CXBa5zXsL3kXvA2JW7y3KEbsGy1Ua3HHF9Yw1X/Y\nfOGs8uR3Kjh38x4HwdbNNE2s7Yw3EAh8OaDYW3l7sUpEXUWUSltsVeMV5zmr\n0P2POP9xPTSSf7pDAh/qGm9B7TDwBjvY8VtQRUl5fh8Ho1cWsUPJ43Wo1huB\n4Y4LXwmb8CZT9DNdT/Ixwy9V2b50o9I+3YukqUPXQt0GJc4PavmQHCobAmTt\nG4NJ\r\n=FN1D\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAZTwPu8ccFhR7bW8bkJtUqDRtTTlfHn7cj+2a/yQA3oAiA6GaC1o/KHi7GfDvaMObFubi4uNACHAfw7EFNKOgvvTQ=="}],"size":12104,"noattachment":false,"key":"/use-context-selector/-/use-context-selector-1.3.2.tgz"},"_npmUser":{"name":"daishi","email":"daishi@axlight.com"},"directories":{},"maintainers":[{"name":"daishi","email":"daishi@axlight.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/use-context-selector_1.3.2_1606991303531_0.6268749850344664"},"_hasShrinkwrap":false,"readme":"# use-context-selector\n\n[![CI](https://img.shields.io/github/actions/workflow/status/dai-shi/use-context-selector/ci.yml?branch=main)](https://github.com/dai-shi/use-context-selector/actions?query=workflow%3ACI)\n[![npm](https://img.shields.io/npm/v/use-context-selector)](https://www.npmjs.com/package/use-context-selector)\n[![size](https://img.shields.io/bundlephobia/minzip/use-context-selector)](https://bundlephobia.com/result?p=use-context-selector)\n[![discord](https://img.shields.io/discord/627656437971288081)](https://discord.gg/MrQdmzd)\n\nReact useContextSelector hook in userland\n\n## Introduction\n\nReact Context and useContext is often used to avoid prop drilling,\nhowever it's known that there's a performance issue.\nWhen a context value is changed, all components that useContext\nwill re-render.\n\nTo solve this issue,\n[useContextSelector](https://github.com/reactjs/rfcs/pull/119)\nis proposed and later proposed\n[Speculative Mode](https://github.com/reactjs/rfcs/pull/150)\nwith context selector support.\nThis library provides the API in userland.\n\nPrior to v1.3, it uses `changedBits=0` feature to stop propagation,\nv1.3 no longer depends on this undocumented feature.\n\n## Install\n\nThis package requires some peer dependencies, which you need to install by yourself.\n\n```bash\nnpm install use-context-selector react scheduler\n```\n\nNotes for library authors:\n\nPlease do not forget to keep `\"peerDependencies\"` and\nnote instructions to let users to install peer dependencies.\n\n## Technical memo\n\nTo make it work like original React context, it uses\n[useReducer cheat mode](https://overreacted.io/a-complete-guide-to-useeffect/#why-usereducer-is-the-cheat-mode-of-hooks) intentionally.\n\nIt also requires `useContextUpdate` to behave better in concurrent rendering.\nIts usage is optional and only required if the default behavior is unexpected.\n\nIf you need a simpler solution, you can use `useSyncExternalStore` without any libraries. See [an example](https://github.com/dai-shi/use-context-selector/issues/109#issuecomment-1785147682).\n\n## Usage\n\n```javascript\nimport { useState } from 'react';\nimport { createRoot } from 'react-dom/client';\n\nimport { createContext, useContextSelector } from 'use-context-selector';\n\nconst context = createContext(null);\n\nconst Counter1 = () => {\n  const count1 = useContextSelector(context, (v) => v[0].count1);\n  const setState = useContextSelector(context, (v) => v[1]);\n  const increment = () =>\n    setState((s) => ({\n      ...s,\n      count1: s.count1 + 1,\n    }));\n  return (\n    <div>\n      <span>Count1: {count1}</span>\n      <button type=\"button\" onClick={increment}>\n        +1\n      </button>\n      {Math.random()}\n    </div>\n  );\n};\n\nconst Counter2 = () => {\n  const count2 = useContextSelector(context, (v) => v[0].count2);\n  const setState = useContextSelector(context, (v) => v[1]);\n  const increment = () =>\n    setState((s) => ({\n      ...s,\n      count2: s.count2 + 1,\n    }));\n  return (\n    <div>\n      <span>Count2: {count2}</span>\n      <button type=\"button\" onClick={increment}>\n        +1\n      </button>\n      {Math.random()}\n    </div>\n  );\n};\n\nconst StateProvider = ({ children }) => (\n  <context.Provider value={useState({ count1: 0, count2: 0 })}>\n    {children}\n  </context.Provider>\n);\n\nconst App = () => (\n  <StateProvider>\n    <Counter1 />\n    <Counter2 />\n  </StateProvider>\n);\n\ncreateRoot(document.getElementById('app')).render(<App />);\n```\n\n## API\n\n<!-- Generated by documentation.js. Update this documentation by updating the source code. -->\n\n### createContext\n\nThis creates a special context for `useContextSelector`.\n\n#### Parameters\n\n*   `defaultValue` **Value**&#x20;\n\n#### Examples\n\n```javascript\nimport { createContext } from 'use-context-selector';\n\nconst PersonContext = createContext({ firstName: '', familyName: '' });\n```\n\n### useContextSelector\n\nThis hook returns context selected value by selector.\n\nIt will only accept context created by `createContext`.\nIt will trigger re-render if only the selected value is referentially changed.\n\nThe selector should return referentially equal result for same input for better performance.\n\n#### Parameters\n\n*   `context` **Context\\<Value>**&#x20;\n*   `selector` **function (value: Value): Selected**&#x20;\n\n#### Examples\n\n```javascript\nimport { useContextSelector } from 'use-context-selector';\n\nconst firstName = useContextSelector(PersonContext, (state) => state.firstName);\n```\n\n### useContext\n\nThis hook returns the entire context value.\nUse this instead of React.useContext for consistent behavior.\n\n#### Parameters\n\n*   `context` **Context\\<Value>**&#x20;\n\n#### Examples\n\n```javascript\nimport { useContext } from 'use-context-selector';\n\nconst person = useContext(PersonContext);\n```\n\n### useContextUpdate\n\nThis hook returns an update function to wrap an updating function\n\nUse this for a function that will change a value in\nconcurrent rendering in React 18.\nOtherwise, there's no need to use this hook.\n\n#### Parameters\n\n*   `context` **Context\\<Value>**&#x20;\n\n#### Examples\n\n```javascript\nimport { useContextUpdate } from 'use-context-selector';\n\nconst update = useContextUpdate();\n\n// Wrap set state function\nupdate(() => setState(...));\n\n// Experimental suspense mode\nupdate(() => setState(...), { suspense: true });\n```\n\n### BridgeProvider\n\nThis is a Provider component for bridging multiple react roots\n\n#### Parameters\n\n*   `$0` **{context: Context\\<any>, value: any, children: ReactNode}**&#x20;\n\n    *   `$0.context` &#x20;\n    *   `$0.value` &#x20;\n    *   `$0.children` &#x20;\n\n#### Examples\n\n```javascript\nconst valueToBridge = useBridgeValue(PersonContext);\nreturn (\n  <Renderer>\n    <BridgeProvider context={PersonContext} value={valueToBridge}>\n      {children}\n    </BridgeProvider>\n  </Renderer>\n);\n```\n\n### useBridgeValue\n\nThis hook return a value for BridgeProvider\n\n#### Parameters\n\n*   `context` **Context\\<any>**&#x20;\n\n## Limitations\n\n*   In order to stop propagation, `children` of a context provider has to be either created outside of the provider or memoized with `React.memo`.\n*   Provider trigger re-renders only if the context value is referentially changed.\n*   Neither context consumers or class components are supported.\n*   The [stale props](https://react-redux.js.org/api/hooks#stale-props-and-zombie-children) issue can't be solved in userland.\n*   Tearing is only avoided if all consumers get data using `useContextSelector`. If you use both props and `use-context-selector` to pass the same data, they may provide inconsistence data for a brief moment. (`02_tearing_spec` fails)\n\n## Examples\n\nThe [examples](examples) folder contains working examples.\nYou can run one of them with\n\n```bash\nPORT=8080 yarn run examples:01_counter\n```\n\nand open <http://localhost:8080> in your web browser.\n\nYou can also try them in codesandbox.io:\n[01](https://codesandbox.io/s/github/dai-shi/use-context-selector/tree/main/examples/01_counter)\n[02](https://codesandbox.io/s/github/dai-shi/use-context-selector/tree/main/examples/02_person)\n[03](https://codesandbox.io/s/github/dai-shi/use-context-selector/tree/main/examples/03_suspense)\n\n## Projects that use use-context-selector\n\n*   [react-tracked](https://github.com/dai-shi/react-tracked)\n*   [use-atom](https://github.com/dai-shi/use-atom)\n*   [react-hooks-fetch](https://github.com/dai-shi/react-hooks-fetch)\n","publish_time":1606991303650,"_cnpm_publish_time":1606991303650,"dist-tags":{"latest":"2.0.0","next":"2.0.0-beta.0"}}