{"name":"use-context-selector","description":"React useContext with selector support in userland","version":"2.0.0-alpha.3","publishConfig":{"tag":"next"},"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.js","module":"./dist/index.esm.js","browser":"./dist/index.umd.js","types":"./dist/src/index.d.ts","sideEffects":false,"scripts":{"compile":"microbundle build --format cjs,es,umd","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":"^9.5.0","@types/jest":"^25.1.4","@types/react":"^16.9.23","@types/react-dom":"^16.9.5","@types/scheduler":"^0.16.1","@typescript-eslint/eslint-plugin":"^2.23.0","@typescript-eslint/parser":"^2.23.0","documentation":"^12.1.4","eslint":"^6.8.0","eslint-config-airbnb":"^18.0.1","eslint-plugin-import":"^2.20.1","eslint-plugin-jsx-a11y":"^6.2.3","eslint-plugin-react":"^7.19.0","eslint-plugin-react-hooks":"^2.5.0","html-webpack-plugin":"^3.2.0","jest":"^25.1.0","microbundle":"^0.12.0-next.8","npm-run-all":"^4.1.5","react":"experimental","react-dom":"experimental","scheduler":"experimental","ts-jest":"^25.2.1","ts-loader":"^6.2.1","typescript":"^3.8.3","webpack":"^4.42.0","webpack-cli":"^3.3.11","webpack-dev-server":"^3.10.3"},"peerDependencies":{"react":">=16.14.0","scheduler":">=0.20.0"},"readme":"# use-context-selector\n\n[![Build Status](https://travis-ci.com/dai-shi/use-context-selector.svg?branch=master)](https://travis-ci.com/dai-shi/use-context-selector)\n[![npm version](https://badge.fury.io/js/use-context-selector.svg)](https://badge.fury.io/js/use-context-selector)\n[![bundle size](https://badgen.net/bundlephobia/minzip/use-context-selector)](https://bundlephobia.com/result?p=use-context-selector)\n\nReact useContext with selector support 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\nv1 uses `calculateChangedBits=()=>0` technique to stop propagation,\nwhile v2 uses `useMutableSource`.\n\n## Install\n\n```bash\nnpm install use-context-selector\n```\n\n## Usage\n\n```javascript\nimport React, { useState } from 'react';\nimport ReactDOM from 'react-dom';\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 = () => 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}>+1</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 = () => 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}>+1</button>\n      {Math.random()}\n    </div>\n  );\n};\n\nconst StateProvider = ({ children }) => {\n  const [state, setState] = useState({ count1: 0, count2: 0 });\n  return (\n    <context.Provider value={[state, setState]}>\n      {children}\n    </context.Provider>\n  );\n};\n\nconst App = () => (\n  <StateProvider>\n    <Counter1 />\n    <Counter2 />\n  </StateProvider>\n);\n\nReactDOM.render(<App />, document.getElementById('app'));\n```\n\n## Migrating from v1 to v2\n\nIn v1:\n\n```js\nuseContextSelector(context, state => state.count);\n```\n\nIn v2:\n\n```js\nuseContext(context, useCallback(state => state.count, []));\n```\n\nIn this case, you can (should) also define the selector function outside render.\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 selector-enabled `useContext`.\n\nIt doesn't pass its value but a ref of the value.\nUnlike the original context provider, this context provider\nexpects the context value to be immutable and stable.\n\n#### Parameters\n\n-   `defaultValue` **Value** \n\n#### Examples\n\n```javascript\nimport { createContext } from 'use-context-selector';\n\nconst PersonContext = createContext({ firstName: '', familyName: '' });\n```\n\n### useContext\n\nThis hook returns context value with optional selector.\n\nIt will only accept context created by `createContext`.\nIt will trigger re-render if only the selected value is referentially changed.\nThe selector must be stable.\nEither define selector outside render or wrap with `useCallback`.\n\nThe selector should return referentially equal result for same input for better performance.\n\n#### Parameters\n\n-   `context` **Context&lt;Value>** \n-   `selector` **function (value: Value): Selected**  (optional, default `identity as(value:Value)=>Selected`)\n\n#### Examples\n\n```javascript\nimport { useContext } from 'use-context-selector';\n\nconst firstName = useContext(PersonContext, state => state.firstName);\n```\n\n### wrapCallbackWithPriority\n\nA utility function to wrap a callback function with higher priority\n\nUse this for a callback that will change a value,\nwhich will be fed into context provider.\n\n#### Parameters\n\n-   `callback` **Callback** \n\n#### Examples\n\n```javascript\nimport { wrapCallbackWithPriority } from 'use-context-selector';\n\nconst wrappedCallback = wrapCallbackWithPriority(callback);\n```\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 isn't solved.\n-   Due to the current useMutableSource limitation, a selector can't return a function. (See `01_basic_spec` wrapping setState)\n-   Tearing is only avoided within the Provider tree. A value outside the Provider will tear. (`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 npm run examples:01_minimal\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/master/examples/01_minimal)\n[02](https://codesandbox.io/s/github/dai-shi/use-context-selector/tree/master/examples/02_typescript)\n\n## Related projects\n\n-   [react-tracked](https://github.com/dai-shi/react-tracked)\n-   [reactive-react-redux](https://github.com/dai-shi/reactive-react-redux)\n","readmeFilename":"README.md","gitHead":"4da247842784c43d88b3cdbced2433b05d14dc4f","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@2.0.0-alpha.3","_nodeVersion":"10.19.0","_npmVersion":"6.14.3","dist":{"integrity":"sha512-tziNN7jNEewNt3M1gkKfbMMsm+BJOl0rStIVrt4M/uHSIyiLVS4EkXtlp3OvOT+xzt2GjrE8pq5Vu7M9c7TOpw==","shasum":"9cfb75769b719b5dc6120192d358236d8c669b6c","tarball":"http://registry-npm.ywwl.com/use-context-selector/download/use-context-selector-2.0.0-alpha.3.tgz","fileCount":12,"unpackedSize":40570,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeehCsCRA9TVsSAnZWagAA+lEP/0AFMwFriS3f7xRaNe15\n5hBfUsW+MzG39aRJlxdumjRa0Qm0+mx8B6qa9vE9Y7n5Kg+VeobGM0pC5T5F\nEqqBhh9Yl7iu1MbgMUHVG5jkJEiSODiUshN47Lgu4r7QoEpXo4i8GDEZ1jbV\n3GZ4wdZb/4lcQsEoTxei/L35mBapAgL9kNvfR8Tv2T9DFLOsnfXAD9JDZMNH\nFvBStULIUOI8UcfQbtEVAMXmZqwN75mneVmv6MqtG+TEqNzjiQ72FH7U0+lk\ncaLbGAjwGsGeRYSpRMFo6j5aL/0jMWT7F7+E6Izjqkc4XymOtfEsVe8WLKLG\nEfFQcCEMGcMbRz6ddwii7O2dSikEkZxhleJpMTWq0cTAUHd76KyejZl0/uEm\njVwp2a2pzClF2ehe110bKAnAvupapJ7OjIPIl/eN19lZ5tdorkt7YeZWb5ej\nHrR6JLmiNzp4YQ9IfLFtV/+N8ay5C1EF41AtqNlZi8kvd+wu0Wn+yWr3WA+E\nuRu2HSXI1ldAlVs8mQslD5Wp+6W3jCvEximLxnKLdQbED5oNPDJfsIog/RxG\nU2Y58AUZjUdyXAYUIWWYaNUWIRJw429oAaVGWYz7UoFC9it7jodhHxGbJwRp\nCXGv0FLGIWsW8XFO4qJZ4s6tIO018jfFWyfaUGo/CsxhC87sCbN+Z5JuJ+LW\nFuAH\r\n=yyHX\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDNtgg8kq0wLvOEy3WOUezJ9H67QzAKecbgQlVD3BfAJAiAfjxxYT2BxDGiypnGzNOxarz2EjHhSBvEhM5mtPznrTQ=="}],"size":8679,"noattachment":false,"key":"/use-context-selector/-/use-context-selector-2.0.0-alpha.3.tgz"},"maintainers":[{"name":"daishi","email":"daishi@axlight.com"}],"_npmUser":{"name":"daishi","email":"daishi@axlight.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/use-context-selector_2.0.0-alpha.3_1585057964371_0.30973645757459245"},"_hasShrinkwrap":false,"publish_time":1585057964512,"_cnpm_publish_time":1585057964512,"dist-tags":{"latest":"2.0.0","next":"2.0.0-beta.0"}}