{"id":16796963,"url":"https://github.com/johnrom/use-optimized-selector","last_synced_at":"2025-07-29T05:34:22.687Z","repository":{"id":57388272,"uuid":"347160768","full_name":"johnrom/use-optimized-selector","owner":"johnrom","description":null,"archived":false,"fork":false,"pushed_at":"2021-03-15T22:32:55.000Z","size":249,"stargazers_count":3,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-07-04T10:08:53.652Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/johnrom.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-03-12T18:29:28.000Z","updated_at":"2021-06-05T09:56:05.000Z","dependencies_parsed_at":"2022-09-02T05:51:49.881Z","dependency_job_id":null,"html_url":"https://github.com/johnrom/use-optimized-selector","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/johnrom/use-optimized-selector","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnrom%2Fuse-optimized-selector","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnrom%2Fuse-optimized-selector/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnrom%2Fuse-optimized-selector/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnrom%2Fuse-optimized-selector/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/johnrom","download_url":"https://codeload.github.com/johnrom/use-optimized-selector/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnrom%2Fuse-optimized-selector/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267633670,"owners_count":24118777,"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","status":"online","status_checked_at":"2025-07-29T02:00:12.549Z","response_time":2574,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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-10-13T09:20:42.344Z","updated_at":"2025-07-29T05:34:22.660Z","avatar_url":"https://github.com/johnrom.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# `use-optimized-selector`\n\nA React Hook to optimize a selector with a comparer. Useful in React bailing out of State updates and renders. Useful for:\n\n- [use-context-selector](https://www.npmjs.com/package/use-context-selector)\n- [use-subscription](https://www.npmjs.com/package/use-subscription)\n\n## Check out the API Reference\n\n- [Api Reference](./docs/API.md)\n\n## Getting Started\n\nGetting started is easy, but it will be good to know how [useMemo](https://reactjs.org/docs/hooks-reference.html#usememo) works in order to confirm your selector is working as expected.\n\n\u003e :warning: Both the selector and comparer passed into this function must be constant or memoized in order to optimize the returned selector. Any time either of those parameters changes, a new selector will be created. In many cases, the library you're using for subscriptions will create a brand new subscription, and return a new, uncached value when memoization is done incorrectly. This will result in less than optimal subscriptions.\n\n\u003e :warning: A second consequence of these optimizations is that you could over-optimize and end up with stale values if you don't take into account everything that could change! For example if there were two worlds named Earth in the examples below with different props, they would be stale when checking `planetNameComparer`! Using something generic like `react-fast-compare` for deep comparison on objects is less prone to mistakes.\n\n### Prerequisites\n\nTo get started, you'll want to have an existing React environment, or spin up a new one with `create-react-app`, `tsdx` or other tools.\n\n### Installing\n\nFirst, install this package:\n\n```bash\n\u003e npm install --save use-optimized-selector\n```\n\nThen import it into your JavaScript or TypeScript file:\n\n### Using `useOptimizedSelector`\n\n#### By itself\n\n```js\nimport { useOptimizedSelector } from 'use-optimized-selector';\n\nconst helloWorldSelector = (hello) =\u003e hello?.world;\n// for example, are they both Earth?\nconst planetNameComparer = (world1, world2) =\u003e world1?.name === world2?.name;\n\nconst MyComponent = () =\u003e {\n  const hello = {\n    world1: { world: { name: \"Earth\" } },\n    world2: { world: { name: \"Earth\" } },\n  };\n\n  const selector = useOptimizedSelector(helloWorldSelector, planetNameComparer);\n\n  // world1 will be returned, because they are considered identical.\n  assert(selector(hello.world1) === hello.world1);\n  assert(selector(hello.world2) === hello.world1);\n  assert(selector(hello.world2) !== hello.world2);\n\n  // now when using state...\n  const [state, setState] = useState(hello.world1);\n\n  // since selector(world2) will return identical to the current value of useState...\n  useEffect(() =\u003e {\n    // setState will bail out!\n    setState(() =\u003e selector(hello.world2));\n  });\n}\n```\n\n#### With useContextSelector\n\n_example from [the `use-context-selector` docs](https://github.com/dai-shi/use-context-selector)_\n\n```js\nimport React, { useState } from 'react';\nimport ReactDOM from 'react-dom';\n\nimport { createContext, useContextSelector } from 'use-context-selector';\nimport { useOptimizedSelector } from 'use-optimized-selector';\nimport { isEqual } from 'react-fast-compare';\n\nconst context = createContext(null);\n\nconst StateProvider = ({ children }) =\u003e {\n  const [state, setState] = useState({ count1: 0, count2: 0 });\n  return (\n    \u003ccontext.Provider value={{state, setState}}\u003e\n      {children}\n    \u003c/context.Provider\u003e\n  );\n};\n\nconst selectCount1 = (value) =\u003e ({\n  count1: value.state.count1,\n  setState: value.setState,\n});\n\n// instead of having to useContextSelector multiple times to get multiple bits,\n// we can call a deep equals function like react-fast-compare's isEqual.\nconst Counter1 = () =\u003e {\n  const optimizedSelector = useOptimizedSelector(selectCount1, isEqual);\n  const { count1, setState } = useContextSelector(context, optimizedSelector);\n  const increment = () =\u003e setState(s =\u003e ({\n    ...s,\n    count1: s.count1 + 1,\n  }));\n  return (\n    \u003cdiv\u003e\n      \u003cspan\u003eCount1: {count1}\u003c/span\u003e\n      \u003cbutton type=\"button\" onClick={increment}\u003e+1\u003c/button\u003e\n      {Math.random()}\n    \u003c/div\u003e\n  );\n};\n```\n\n#### With Subscriptions\n\n```js\n// There's an imaginary input where a person might type \"012\".\n// Normally, there would be 3 updates to state with different world instances in that time.\n// By using useOptimizedSelector, we can make this 1 update.\nconst hello = {\n  \"0\": { world: { name: \"Earth\" } },\n  \"01\": { world: { name: \"Earth\" } },\n  \"012\": { world: { name: \"Earth\" } },\n}\n\nconst MyComponent = (input) =\u003e {\n  const optimizedSelector = useOptimizedSelector(\n    // memoize to return same function unless input changes\n    useMemo(\n      () =\u003e selectHelloWorld(hello[input.value]),\n      [input]\n    )\n    // compare name of world\n    planetNameComparer,\n  );\n\n  // https://github.com/facebook/react/tree/9198a5cec0936a21a5ba194a22fcbac03eba5d1d/packages/use-subscription\n  const subscription = useMemo(\n    () =\u003e ({\n      getCurrentValue: optimizedSelector,\n      subscribe: callback =\u003e {\n        input.addEventListener(\"change\", callback);\n        return () =\u003e input.removeEventListener(\"change\", callback);\n      }\n    }),\n\n    // Re-subscribe any time our input changes, or the optimized selector changes\n    // this shouldn't be something that happens often,\n    // or you should rethink your selector\n    [input, optimizedSelector]\n  );\n\n  // we'll get undefined, or a world. if typing 0, 1, 2, we'll only get one update.\n  const world = useSubscription(subscription);\n\n  return \u003cp\u003e{world?.name ?? \"No World\"}\u003c/p\u003e;\n}\n```\n\n## Authors\n\n* [John Rom](https://johnrom.com)\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details\n\n## Acknowledgments\n\n* Original Concept [@dai-shi](https://github.com/dai-shi) [useContextSelector](https://github.com/dai-shi/use-context-selector/issues/19#issuecomment-767198162)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnrom%2Fuse-optimized-selector","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjohnrom%2Fuse-optimized-selector","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnrom%2Fuse-optimized-selector/lists"}