{"id":13661005,"url":"https://github.com/davidgilbertson/react-recollect","last_synced_at":"2025-04-04T11:11:01.015Z","repository":{"id":33260021,"uuid":"155156974","full_name":"davidgilbertson/react-recollect","owner":"davidgilbertson","description":"State management for React","archived":false,"fork":false,"pushed_at":"2023-01-06T00:45:33.000Z","size":3853,"stargazers_count":403,"open_issues_count":27,"forks_count":10,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-03-28T10:06:36.622Z","etag":null,"topics":["immutability","react","state-management"],"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/davidgilbertson.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-10-29T05:32:45.000Z","updated_at":"2024-08-21T06:24:20.000Z","dependencies_parsed_at":"2023-01-15T00:15:21.710Z","dependency_job_id":null,"html_url":"https://github.com/davidgilbertson/react-recollect","commit_stats":null,"previous_names":[],"tags_count":48,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidgilbertson%2Freact-recollect","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidgilbertson%2Freact-recollect/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidgilbertson%2Freact-recollect/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidgilbertson%2Freact-recollect/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/davidgilbertson","download_url":"https://codeload.github.com/davidgilbertson/react-recollect/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247166168,"owners_count":20894654,"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":["immutability","react","state-management"],"created_at":"2024-08-02T05:01:28.448Z","updated_at":"2025-04-04T11:11:00.983Z","avatar_url":"https://github.com/davidgilbertson.png","language":"TypeScript","funding_links":[],"categories":["TypeScript","List"],"sub_categories":[],"readme":"![version](https://img.shields.io/github/package-json/v/davidgilbertson/react-recollect?label=Version)\n![Tests](https://github.com/davidgilbertson/react-recollect/workflows/Node.js%20CI/badge.svg)\n\n# React Recollect\n\n## What?\n\nRecollect is a state management library for React, an alternative to Redux.\n\n## Why?\n\nRecollect aims to solve two problems with the traditional React/Redux approach:\n\n1. Immutability logic is verbose, complicated, and prone to bugs.\n2. Developers must write code to define which parts of the store a component\n   plans to use. Even then, components can be re-rendered when they don't use\n   the data that has just changed.\n\n## How?\n\n1. The Recollect store is immutable, but the implementation is hidden. So, you\n   can interact with the store as though it were a plain JavaScript object.\n2. Recollect records access to the store during the render cycle of a component.\n   When a property in your store changes, only components that use that property\n   are re-rendered.\n\nThe result is simpler code and a faster app. Take it for a spin in this\n[CodeSandbox](https://codesandbox.io/s/github/davidgilbertson/react-recollect/tree/master/demo).\n\n---\n\n**Caution:** there is no support for any version of IE, Opera mini, or Android\nbrowser 4.4 (because Recollect uses the `Proxy` object). Check out the latest\nusage stats for proxies at [caniuse.com](https://caniuse.com/#feat=proxy).\n\n# Quick start\n\n```\nnpm i react-recollect\n```\n\nThe `store` object and the `collect` function are all you need to know to get\nstarted.\n\nThe store is where your data goes; you can treat it just like you'd treat any\nJavaScript object. You can import, read from, and write to the store in any\nfile.\n\nHere's some code doing normal things with the normal-looking `store`:\n\n```js\nimport { store } from 'react-recollect';\n\nstore.tasks = ['one', 'two', 'three']; // Fine\n\nstore.tasks.push('four'); // Good\n\nstore.site = { title: 'Page one' }; // Acceptable\n\nObject.assign(store.site, { title: 'Page two' }); // Neato\n\nstore.site.title += '!'; // Exciting!\n\ndelete store.site; // Seems extreme, but works a treat\n\nstore = 'foo'; // Nope! (can't reassign a constant)\n```\n\n\u003e Play with this code in a\n\u003e [CodeSandbox](https://codesandbox.io/s/normal-store-doing-normal-things-5wz77)\n\nThese operations behave just like you'd expect them to, except none of them\n_mutate_ the store contents. In fact, it's impossible to mutate the data in a\nRecollect store.\n\nNext up: the `collect` function. This wraps a React component, allowing\nRecollect to take care of it. This will provide the store as a prop, and update\nthe component when it needs updating.\n\nHere's `collect` and `store` working together:\n\n```jsx harmony\nimport { collect } from 'react-recollect';\n\nconst TaskList = ({ store }) =\u003e (\n  \u003cdiv\u003e\n    {store.tasks.map((task) =\u003e (\n      \u003cdiv\u003e{task.name}\u003c/div\u003e\n    ))}\n\n    \u003cbutton\n      onClick={() =\u003e {\n        store.tasks.push({\n          name: 'A new task',\n          done: false,\n        });\n      }}\n    \u003e\n      Add a task\n    \u003c/button\u003e\n  \u003c/div\u003e\n);\n\nexport default collect(TaskList);\n```\n\nCongratulations my friend, you've finished learning Recollect. I am very proud\nof you.\n\nGo have a play, and when you're ready for more readme, come back to read on.\n\nIf you've got a question, make sure to read the [FAQ](#faq) to see if your Q is\nFA. Otherwise, open a GitHub issue.\n\n---\n\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n\n- [Installation](#installation)\n  - [NPM](#npm)\n  - [CDN](#cdn)\n- [API](#api)\n  - [`store`](#store)\n  - [`collect(ReactComponent)`](#collectreactcomponent)\n  - [`afterChange(callback)`](#afterchangecallback)\n  - [`initStore(data)`](#initstoredata)\n    - [On the server](#on-the-server)\n    - [In the browser](#in-the-browser)\n  - [`batch(callback)`](#batchcallback)\n  - [`useProps(propArray)`](#usepropsproparray)\n  - [`PropTypes`](#proptypes)\n  - [`window.__RR__`](#window__rr__)\n    - [Time travel](#time-travel)\n- [Usage with TypeScript](#usage-with-typescript)\n  - [Your store](#your-store)\n  - [Using collect](#using-collect)\n- [Project structure guidelines](#project-structure-guidelines)\n  - [Selectors](#selectors)\n  - [Updaters](#updaters)\n    - [Loading data with an updater](#loading-data-with-an-updater)\n    - [Asynchronous updaters](#asynchronous-updaters)\n    - [Testing an updater](#testing-an-updater)\n- [FAQ](#faq)\n  - [How does it work?](#how-does-it-work)\n  - [What sort of stuff can go in the store?](#what-sort-of-stuff-can-go-in-the-store)\n    - [Map and Set limitations](#map-and-set-limitations)\n  - [When will my components be re-rendered?](#when-will-my-components-be-re-rendered)\n  - [How many components should I wrap in `collect`?](#how-many-components-should-i-wrap-in-collect)\n  - [Can I use this with class-based components and functional components?](#can-i-use-this-with-class-based-components-and-functional-components)\n  - [Hooks?](#hooks)\n  - [Will component state still work?](#will-component-state-still-work)\n  - [Do lifecycle methods still fire?](#do-lifecycle-methods-still-fire)\n    - [Why isn't my `componentDidUpdate` code firing?](#why-isnt-my-componentdidupdate-code-firing)\n  - [Can I use this with `shouldComponentUpdate()`?](#can-i-use-this-with-shouldcomponentupdate)\n  - [Can I wrap a `PureComponent` or `React.memo` in `collect`?](#can-i-wrap-a-purecomponent-or-reactmemo-in-collect)\n  - [Can I use this with `Context`?](#can-i-use-this-with-context)\n  - [Can I use this with `ref`s?](#can-i-use-this-with-refs)\n  - [Can I have multiple stores?](#can-i-have-multiple-stores)\n  - [Can I use Recollect without React?](#can-i-use-recollect-without-react)\n  - [I'm getting a `no-param-reassign` ESLint error](#im-getting-a-no-param-reassign-eslint-error)\n  - [Tell me about your tests](#tell-me-about-your-tests)\n  - [How big is it?](#how-big-is-it)\n  - [Is reading/writing via a proxy slow?](#is-readingwriting-via-a-proxy-slow)\n- [Dependencies](#dependencies)\n- [Alternatives](#alternatives)\n- [Is it really OK to drop support for IE?](#is-it-really-ok-to-drop-support-for-ie)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\n# Installation\n\n## NPM\n\nInstall with npm:\n\n```\nnpm install react-recollect\n```\n\nOr Yarn:\n\n```\nyarn add react-recollect\n```\n\nYou can then import it in the usual ways:\n\n```js\nimport { collect, store } from 'react-recollect';\n\n// or\nconst { collect, store } = require('react-recollect');\n```\n\n## CDN\n\nYou can also load Recollect from the [unpkg CDN](https://unpkg.com).\n\n```html\n\u003cscript src=\"https://unpkg.com/react-recollect\"\u003e\u003c/script\u003e\n```\n\nThis will create a global `ReactRecollect` object. See\n[demo/public/browser.html](./demo/public/browser.html) for a working example\nwith React and Babel.\n\nIt's a good idea to reference an exact version in the URL, so that it can be\ncached. [Click here](https://unpkg.com/react-recollect) to get the full URL.\n\n# API\n\n## `store`\n\n\u003e \u003csmall\u003eAdded in `1.0.0`\u003c/small\u003e\n\nThe `store` object that Recollect exposes is designed to behave like a plain old\nJavaScript object. But it's a bit different because it's immutable. You can\nwrite code as though you _were_ mutating it, but internally it will clone the\nparts of itself that it needs to clone to apply your changes, without mutating\nanything.\n\nWhen the store is then passed to a component, React can do its clever shallow\ncomparisons to know whether something has changed and update efficiently.\n\n## `collect(ReactComponent)`\n\n\u003e \u003csmall\u003eAdded in `1.0.0`\u003c/small\u003e\n\nWhen you wrap a component in `collect`, Recollect will:\n\n- Provide the store object as a prop.\n- Collect information about the data the component needs to render (which\n  properties in the store it read while rendering).\n- Re-render the component when that data changes.\n\nInternally, Recollect 'subscribes' components to property 'paths'. For example,\nthis component would be subscribed to the `store.page.title` path and\nre-rendered when that property changes.\n\n```jsx harmony\nimport { collect } from 'react-recollect';\n\nconst Header = ({ store }) =\u003e (\n  \u003cheader\u003e\n    \u003ch1\u003e{store.page.title}\u003c/h1\u003e\n  \u003c/header\u003e\n);\n\nexport default collect(Header);\n```\n\n## `afterChange(callback)`\n\n\u003e \u003csmall\u003eAdded in `1.0.0`, the below applies to `4.0.0` and up\u003c/small\u003e\n\n`afterChange` will call the provided callback whenever the store updates.\n\nThe callback receives an event object with these properties:\n\n- `store` — the store\n- `changedProps` — the 'paths' of the properties that changed. E.g.\n  `['tasks.2.done', 'tasks.4.done']`\n- `renderedComponents` — an array of the components that were updated\n\nFor example, if you want to save the current page to local storage when a\nparticular value in the store changes, you could do the following (anywhere in\nyour app).\n\n```js\nimport { afterChange } from 'react-recollect';\n\nafterChange((e) =\u003e {\n  if (e.changedProps.includes('currentPage')) {\n    localStorage.currentPage = e.store.currentPage;\n  }\n});\n```\n\n## `initStore(data)`\n\n\u003e \u003csmall\u003eAdded in `2.4.0`\u003c/small\u003e\n\nThe `initStore` function will _replace_ the contents of the store with the\nobject you pass in.\n\n`data` is optional — if you don't pass anything, the store will be emptied\n(useful in tests).\n\nIf you're only using Recollect in the browser, you don't _need_ to use this, but\nit's handy to set the default state of your store. You can also use\n`Object.assign(store, { foo: 'bar' })` if you want to shallow-merge new data\ninto the store.\n\nWhen you render on the server though, you _do_ need to initialize the store,\nbecause unlike a browser, a server is shared between many users and state needs\nto be fresh for each request.\n\n### On the server\n\nHere's a minimal implementation of server-side rendering with Express and\nRecollect.\n\n```jsx harmony\n// Create an express app instance\nconst app = express();\n\n// Read the HTML template on start up (this is the create-react-app output)\nconst htmlTemplate = fs.readFileSync(\n  path.resolve(__dirname, '../../build/index.html'),\n  'utf8'\n);\n\n// We'll serve our page to requests at '/'\napp.get('/', async (req, res) =\u003e {\n  // Fetch some data\n  const tasks = await fetchTasksForUser(req.query.userId);\n\n  // Populate the Recollect store (discarding any previous state)\n  initStore({ tasks });\n\n  // Render the app. Components will read from the Recollect store as usual\n  const appMarkup = ReactDOMServer.renderToString(\u003cApp /\u003e);\n\n  // Serialize the store (replacing left tags for security)\n  const safeStoreString = JSON.stringify(store).replace(/\u003c/g, '\\\\u003c');\n\n  // Insert the markup and the data into the template\n  const htmlWithBody = htmlTemplate.replace(\n    '\u003cdiv id=\"root\"\u003e\u003c/div\u003e',\n    `\u003cdiv id=\"root\"\u003e${appMarkup}\u003c/div\u003e\n    \u003cscript\u003ewindow.__PRELOADED_STATE__ = ${safeStoreString};\u003c/script\u003e`\n  );\n\n  // Return the rendered page to the user\n  res.send(htmlWithBody);\n});\n```\n\nIt's important that you populate the store using `initStore`, and do so before\nrendering your app with `ReactDOMServer.renderToString()`.\n\nThis is because your Node server might receive several requests from several\nusers at the same time. All of these requests share the same global state,\nincluding the `store` object.\n\nSo, you must make sure that for each request, you empty the store, populate it\nwith the appropriate data for the request, and render the markup at the same\ntime. And by 'at the same time', I mean _synchronously_.\n\n### In the browser\n\nIn the entry point to your app, right before you call `ReactDOM.hydrate()`, call\n`initStore()` with the data that you sent from the server:\n\n```jsx harmony\nimport { initStore } from 'react-recollect';\n\n// other stuff\n\ninitStore(window.__PRELOADED_STATE__);\n\nReactDOM.hydrate(\u003cApp /\u003e, document.getElementById('root'));\n```\n\nThis will take the data that you saved in the DOM on the server and fill up the\nRecollect store with it. You should only init the store once, before the initial\nrender.\n\nNote that `initStore` will trigger a render of collected components where\napplicable, and will fire `afterChange`.\n\n## `batch(callback)`\n\n\u003e \u003csmall\u003eAdded in `4.0.0`\u003c/small\u003e\n\nThe `batch` function allows you to update the store multiple times, and be\nguaranteed that components will only be updated after all updates are made.\n\nThe callback function will be called immediately and should only contain\nsynchronous code.\n\n```js\nimport { batch } from 'react-recollect';\n\nconst fetchData = async () =\u003e {\n  const { posts, users, meta } = await fetch('/api').then((response) =\u003e\n    response.json()\n  );\n\n  batch(() =\u003e {\n    store.posts = posts;\n    store.users = users;\n    store.meta = meta;\n  });\n\n  // now a render will be triggered for any components that use this data\n};\n```\n\nNote that React already does a good job of batching multiple updates into a\nsingle render cycle. So only clutter up your code with `batch` if it results in\nan actual performance improvement.\n\n## `useProps(propArray)`\n\n\u003e \u003csmall\u003eAdded in `5.1.0`\u003c/small\u003e\n\nIn most cases, you can rely on Recollect to know what data your component\nrequires to render. However, Recollect can't know that your component will\nrequire a property in the _future_. If you reference a property:\n\n- in `componentDidUpdate` (and nowhere else), or\n- in UI that is only revealed after a change in state (perhaps a modal or\n  drop-down)\n\n... then Recollect won't know about it and your component won't be subscribed to\nchanges in that property.\n\nYou can tell Recollect _“I want to know if any of these properties change”_ by\npassing an array of store objects to the `useProps` function, like so:\n\n```js\nimport { collect, useProps } from 'react-recollect';\n\nconst MyComponent = ({ store }) =\u003e {\n  const [showHiddenMessage, setShowHiddenMessage] = useState(false);\n\n  // \"This component might read `store.hiddenMessage` in the future\"\n  useProps([store.hiddenMessage]);\n\n  return (\n    \u003cdiv\u003e\n      {showHiddenMessage \u0026\u0026 \u003cp\u003e{store.hiddenMessage}\u003c/p\u003e}\n\n      \u003cbutton onClick={() =\u003e setShowHiddenMessage(true)}\u003e\n        Show hidden message\n      \u003c/button\u003e\n    \u003c/div\u003e\n  );\n};\n\nexport default collect(MyComponent);\n```\n\nAlthough `useProps` starts with the word 'use', it doesn't require React's Hooks\nmechanism, so it works just fine in versions before React 16.8. (For the\ncurious, the implementation is literally just `propArray.includes(0)`.)\n\nCheck out [these tests](tests/unit/useProps.test.tsx) for more usage examples.\n\n## `PropTypes`\n\n\u003e \u003csmall\u003eAdded in `5.2.0`\u003c/small\u003e\n\nAs you've learnt by now, Recollect works by 'recording' which properties your\ncomponent reads from the store while it renders. This poses a problem if you use\nthe `prop-types` library, because it is going to read _every property_ that you\ndefine in your prop types.\n\nThis could result in your component being subscribed to changes in a property it\ndoesn't use, potentially concealing a problem that would only become apparent in\nproduction (where prop types aren't checked).\n\nFor this reason, `react-recollect` exports a proxied version of `prop-types`.\nIt's exactly the same as the normal `prop-types` library, except that Recollect\nwill pause its recording while your props are being checked.\n\n```jsx harmony\nimport { PropTypes } from 'react-recollect';\n\nconst MyComponent = (props) =\u003e \u003ch1\u003e{props.title}\u003c/h1\u003e;\n\nMyComponent.propTypes = {\n  title: PropTypes.string.isRequired,\n};\n\nexport default MyComponent;\n```\n\nWe recommended that you uninstall `prop-types` from your project and replace its\nusages with the Recollect version. That way no one can accidentally use the\n'wrong' `prop-types` (if they didn't get this far in the readme).\n\nIf you use `@types/prop-types` you can uninstall that too, the types are built\ninto `react-recollect`.\n\n## `window.__RR__`\n\nUse `window.__RR__` to inspect or edit the Recollect store in your browser's\nconsole.\n\n`__RR__` does not form part of the official API and should not be used in\nproduction. It might change between versions without warning and without\nrespecting semver.\n\nIt has these properties, available in development or production:\n\n- `debugOn()` will turn on debugging. This shows you what's updating in the\n  store and which components are being updated as a result, and what data those\n  components are reading. Note that this can have a negative impact on\n  performance if you're reading thousands of properties in a render cycle. Note\n  also that it will 'collapse' all other console logs into the output (important\n  for debugging, but not ideal a lot of the time).\n- `debugOff()` will surprise you\n- `internals` exposes some interesting things.\n\nVia the `internals` object, you can get a reference to the store, which can be\nhandy for troubleshooting. For example, typing\n`__RR__.internals.store.loading = true` in the console would update the store\nand re-render the appropriate components.\n\nIf you just log the store to the console, you will see a strange object littered\nwith `[[Handler]]` and `[[Target]]` props. These are the proxies. All you need\nto know is that `[[Target]]` is the actual object you put in the store.\n\nDuring development there are two more methods to help you inspect your app:\n\n- `getListenersByComponent()` will show you which store properties each\n  component is subscribed to.\n- `getComponentsByListener()` is the inverse: it will show you which components\n  are subscribed to which store properties.\n\nYou can optionally pass a string or regular expression to filter the results.\n\n```js\n// Which components are subscribed to the user's status\n__RR__.getComponentsByListener('user.status');\n\n// What is \u003cMyComponent\u003e subscribed to?\n__RR__.getListenersByComponent('MyComponent');\n\n// What about the \u003cTask\u003e component where the prop `taskId` is 2?\n__RR__.getListenersByComponent('Task2', (props) =\u003e props.taskId);\n```\n\nCheck out [the debug test suite](./tests/unit/debug.test.tsx) for more examples.\n\n### Time travel\n\n\u003e \u003csmall\u003eAdded in `5.2.3`\u003c/small\u003e\n\nYou can navigate through the history of changes to the store with the below\nfunctions (in your DevTools console):\n\n- `__RR__.back()` will go back to the state before the last store change.\n- `__RR__.forward()` will go forward again.\n- `__RR__.goTo(index)` will go to a particular index in the history.\n- `__RR__.getHistory()` will log out the entire history.\n- `__RR__.clearHistory()` clears the history.\n- `__RR__.setHistoryLimit(limit)` limits the number of store instances kept in\n  history. Defaults to `50`. Setting to `0` disables time travel. Is stored in\n  local storage.\n\nIf you update the store with `initStore` or execute multiple updates within the\n`batch` function callback, those changes are recorded as a single history event.\n\nNote that these time travel functions are only available during development, not\nin the production build.\n\n# Usage with TypeScript\n\n## Your store\n\nDefine the shape of your recollect `store` like this:\n\n```ts\ndeclare module 'react-recollect' {\n  interface Store {\n    someProp?: string[];\n    somethingElse?: string;\n  }\n}\n```\n\nPut this in a declarations file such as `src/types/RecollectStore.ts`.\n\n## Using collect\n\nComponents wrapped in `collect` must define `store` in `props` — use the\n`WithStoreProp` interface for this:\n\n```tsx\nimport { collect, WithStoreProp } from 'react-recollect';\n\ninterface Props extends WithStoreProp {\n  someComponentProp: string;\n}\n\nconst MyComponent = ({ store, someComponentProp }: Props) =\u003e (\n  // \u003c your awesome JSX here\u003e\n);\n\nexport default collect(MyComponent);\n```\n\nIf the only prop your component needs is `store`, you can use `WithStoreProp`\ndirectly.\n\n```tsx\nimport { WithStoreProp } from 'react-recollect';\n\nconst MyComponent = ({ store }: WithStoreProp) =\u003e \u003cdiv\u003eHello {store.name}\u003c/div\u003e;\n```\n\nRecollect is written in TypeScript, so you can check out the\n[integration tests](./tests/integration) if you're not sure how to implement\nsomething.\n\n(If you've got Mad TypeScript Skillz and would like to contribute, see if you\ncan work out how to resolve the `@ts-ignore` in\n[the collect module](./src/collect.tsx)).\n\n# Project structure guidelines\n\nThe ideas described in this section aren't part of the Recollect API, they're\nsimply a guide.\n\nTwo concepts are described in this section (neither of them new):\n\n- **Selectors** contain logic for retrieving and data from the store.\n\n- **Updaters** contain logic for updating the store. Updaters also handle\n  reading/writing data from outside the browser (e.g. loading data over the\n  network or from disk).\n\n![Cycle of life](cycle.png)\n\nIn a simple application, you don't need to explicitly think in terms of updaters\nand selectors. For example:\n\n- defining `checked={task.done}` in a checkbox is a tiny little 'selector'\n- executing `task.done = true` when a user clicks that checkbox is a tiny little\n  'updater'\n\nBut as your app grows, it's important to keep your components focused on UI —\nyou don't want 200 lines of logic in the `onClick` event of a button.\n\nSo there will come a point where moving code out of your components into\ndedicated files is necessary, and at this point, updaters and selectors will\nserve as useful concepts for organization.\n\nIn the examples below, I'll use a directory structure like this:\n\n```\n/my-app\n └─ src\n    ├─ components\n    ├─ store\n    │  ├─ selectors\n    │  └─ updaters\n    └─ utils\n```\n\n(Fun fact: _selector_ ends in 'or' because 'select' is derived from latin, while\n_updater_ ends in 'er' because it was made up in 1941 and 'or' had gone out of\nstyle.)\n\n## Selectors\n\nA simple case for a selector would be to return all incomplete tasks, sorted by\ndue date.\n\n```js\nexport const getIncompleteTasksSortedByDueDate = (store) =\u003e {\n  const tasks = store.tasks.slice();\n\n  return tasks\n    .sort((a, b) =\u003e a.dueDate - b.dueDate)\n    .filter((task) =\u003e !task.done);\n};\n```\n\nYou would then use this function by importing it and referencing it in your\ncomponent:\n\n```jsx harmony\nimport { getIncompleteTasksSortedByDueDate } from '../store/selectors/taskSelectors';\n\nconst TaskList = ({ store }) =\u003e {\n  const tasks = getIncompleteTasksSortedByDueDate(store);\n\n  return (\n    \u003cdiv\u003e\n      {tasks.map((task) =\u003e (\n        \u003cTask key={task.id} task={task} /\u003e\n      ))}\n    \u003c/div\u003e\n  );\n};\n```\n\nIn this example, I'm passing the `store` object into the `selector`. But you\ncould also do `import { store } from 'react-recollect'` in the selector file.\n(In Recollect version 4 and earlier, you _had_ to pass the store through. From\nv5 onwards, you can use `props.store` _or_ import the store.)\n\nMaybe we want to conditionally show either all tasks or only incomplete tasks.\nLet's create a second selector. And while we're at it, move repeated sorting\ncode out into its own function:\n\n```js\nconst getTasksSortedByDate = (tasks) =\u003e {\n  const sortedTasks = tasks.slice();\n\n  return sortedTasks.sort((a, b) =\u003e a.dueDate - b.dueDate);\n};\n\nexport const getAllTasksSortedByDueDate = (store) =\u003e\n  getTasksSortedByDate(store.tasks);\n\nexport const getIncompleteTasksSortedByDueDate = (store) =\u003e\n  getTasksSortedByDate(store.tasks).filter((task) =\u003e !task.done);\n```\n\nAnd here's a more complex component with local state and a dropdown to show\neither all tasks or just those that aren't done:\n\n```jsx harmony\nclass TaskList extends PureComponent {\n  state = {\n    filter: 'all',\n  };\n\n  render() {\n    const { store } = this.props;\n\n    const tasks =\n      this.state.filter === 'all'\n        ? getAllTasksSortedByDueDate(store)\n        : getIncompleteTasksSortedByDueDate(store);\n\n    return (\n      \u003cdiv\u003e\n        {tasks.map((task) =\u003e (\n          \u003cTask key={task.id} task={task} /\u003e\n        ))}\n\n        \u003cselect\n          value={this.state.filter}\n          onChange={(e) =\u003e {\n            this.setState({ filter: e.target.value });\n          }}\n        \u003e\n          \u003coption value=\"all\"\u003eAll tasks\u003c/option\u003e\n          \u003coption value=\"incomplete\"\u003eIncomplete tasks\u003c/option\u003e\n        \u003c/select\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\nNow, when a user changes the dropdown, the component state will update, a\nre-render will be triggered, and as a result, a different selector will be used.\n\n## Updaters\n\nAn 'updater' is a function that updates the store in some way. As with\nselectors, you don't _need_ to use updaters, they're just an organizational\nconcept to minimize the amount of data logic you have in your component files.\n\nA simple case for an updater would be to mark all tasks as done in a todo app:\n\n```js\nimport { store } from 'react-recollect';\n\nexport const markAllTasksAsDone = () =\u003e {\n  store.tasks.forEach((task) =\u003e {\n    task.done = true;\n  });\n};\n```\n\nYou would reference this from a component by importing it then calling it in\nresponse to some user action:\n\n```jsx harmony\nimport { markAllTasksAsDone } from '../store/updaters/taskUpdaters';\n\nconst Footer = () =\u003e (\n  \u003cbutton onClick={markAllTasksAsDone}\u003eMark all as done\u003c/button\u003e\n);\n\nexport default Footer;\n```\n\nYou don't need to 'dispatch' an 'action' from an 'action creator' to a\n'reducer'; you're just calling a function that updates the store.\n\nAnd since these are just plain functions, they're 'composable'. Or in other\nwords, if you want an updater that calls three other updaters, go for it.\n\n### Loading data with an updater\n\nLet's create an updater that loads some tasks from an api when our app mounts.\nIt will need to:\n\n1. Set a loading indicator to true\n2. Fetch some tasks from a server\n3. Save the data to the store\n4. Set the loading indicator to false\n\n```js\nexport const loadTasksFromServer = async () =\u003e {\n  store.loading = true;\n\n  store.tasks = await fetchJson('/api/get-my-tasks');\n\n  store.loading = false;\n};\n```\n\nYou might call this function like so:\n\n```js\nimport { loadTasksFromServer } from '../store/updaters/taskUpdaters';\n\nclass TaskList extends React.Component {\n  componentDidMount() {\n    loadTasksFromServer();\n  }\n\n  render() {\n    // just render stuff\n  }\n}\n```\n\n### Asynchronous updaters\n\nDid you notice that we've already covered the super-complex topic of\nasynchronicity? You can update the Recollect store whenever you like, so you\ndon't need to do anything special to get asynchronous code to work.\n\n### Testing an updater\n\nLet's write a unit test to call our updater and assert that it put the correct\ndata in the store. The function we're testing is async, so our test will be\nasync too:\n\n```js\ntest('loadTasksFromServer should update the store', async () =\u003e {\n  // Execute the updater\n  await loadTasksFromServer();\n\n  // Check that the final state of the store is what we expected\n  expect(store).toEqual(\n    expect.objectContaining({\n      loading: false,\n      tasks: [\n        {\n          id: 1,\n          name: 'Fetched task',\n          done: false,\n        },\n      ],\n    })\n  );\n});\n```\n\nPretty easy, right?\n\nWe can make it less easy.\n\nMaybe we want to assert that `loading` was set to `true`, then the tasks loaded,\nand then `loading` was set to `false` again.\n\nWell, Recollect exports an `afterChange` function designed to call a callback\nevery time the store changes. If we pass it a Jest mock function, Jest will\nconveniently keep a record of each time the store changed.\n\nAlso, no one likes half an example, so here's the entire test file:\n\n```js\nimport { afterChange, store } from 'react-recollect';\nimport { loadTasksFromServer } from './taskUpdaters';\n\njest.mock('../../utils/fetchJson', () =\u003e async () =\u003e [\n  {\n    id: 1,\n    name: 'Fetched task',\n    done: false,\n  },\n]);\n\ntest('loadTasksFromServer should update the store', async () =\u003e {\n  // Create a mock\n  const afterChangeHandler = jest.fn();\n\n  // Pass the mock to afterChange. Jest will record calls to this function\n  // and therefore record calls to update the store.\n  afterChange(afterChangeHandler);\n\n  // Execute our updater\n  await loadTasksFromServer();\n\n  // afterChangeHandler will be called with the new version of the store and the path that was changed\n  const firstChange = afterChangeHandler.mock.calls[0][0];\n  const secondChange = afterChangeHandler.mock.calls[1][0];\n  const thirdChange = afterChangeHandler.mock.calls[2][0];\n\n  expect(firstChange.changedProps[0]).toBe('loading');\n  expect(firstChange.store.loading).toBe(true);\n\n  expect(secondChange.changedProps[0]).toBe('tasks');\n  expect(secondChange.store.tasks.length).toBe(1);\n\n  expect(thirdChange.changedProps[0]).toBe('loading');\n  expect(thirdChange.store.loading).toBe(false);\n\n  // Check that the final state of the store is what we expected\n  expect(store).toEqual(\n    expect.objectContaining({\n      loading: false,\n      tasks: [\n        {\n          id: 1,\n          name: 'Fetched task',\n          done: false,\n        },\n      ],\n    })\n  );\n});\n```\n\n# FAQ\n\n## How does it work?\n\nEvery object you add to the Recollect store gets wrapped in a `Proxy`. These\nproxies allow Recollect to intercept reads and writes. It's similar to defining\ngetters and setters, but far more powerful.\n\nIf you were to execute the code below, that `site` object would be wrapped in a\nproxy.\n\n```js\nstore.site = {\n  title: 'Page one',\n};\n```\n\n(Items are deeply/recursively wrapped, not just the top level object you add.)\n\nNow, if you execute the code `store.site.title = 'Page two'`, Recollect won't\nmutate the `site` object to set the `title` property. Recollect will block the\noperation and instead create a clone of the object where `title` is\n`'Page two'`. Recollect keeps a reference between the old and the new `site`\nobjects, so any attempt to read from or write to the 'old version' will be\nredirected to the 'new version' of that object.\n\nIn addition to intercepting _write_ operations, the proxies also allow Recollect\nto know when data is being _read_ from the store. When you wrap a component in\n`collect`, you're instructing Recollect to monitor when that component starts\nand stops rendering. Any read from the store while a component is rendering\nresults in that component being 'subscribed' to the property that was read.\n\nBringing it all together: when some of your code attempts to write to the store,\nRecollect will clone as described above, then notify all the components that use\nthe property that was updated, passing those components the 'next' version of\nthe store.\n\n## What sort of stuff can go in the store?\n\nYou can store anything that's valid JSON. If that's all you want to do, you can\nskip the rest of this section.\n\n\u003e \u003csmall\u003eThe below applies to `4.0.0` and up\u003c/small\u003e\n\nRecollect will store data of any type, including (but not limited to):\n\n- `undefined`\n- `Map`\n- `Set`\n- `RegExp` objects\n- `Date` objects\n\nRecollect will _monitor_ changes to:\n\n- Primitives (string, number, boolean, null, undefined, symbol)\n- Plain objects\n- Arrays\n- Maps (see limitations below)\n- Sets (see limitations below)\n\nRecollect will store, but not monitor attempted mutations to other objects. For\nexample:\n\n- `store.date = new Date()` is fine.\n- `store.date.setDate(7)` will not trigger an update.\n- `store.uIntArray = new Uint8Array([3, 2, 1])` is fine.\n- `store.uIntArray.sort()` will not trigger an update.\n\nThe same applies to `WeakMap`, `DataView`, `ArrayBuffer` and any other object\nyou can think of.\n\nIf there's a data type you want to store and mutate that isn't supported, log an\nissue and we'll chat.\n\nOther things that aren't supported (or haven't been tested):\n\n- Functions (e.g. getters, setters, or other methods)\n- Class instances (if this would be useful to you, log an issue and we'll chat)\n- Properties defined with `Object.defineProperty()`\n- String properties on arrays, Maps and Sets (I don't mean string _keys_ in\n  maps, I mean actually creating a property on the object itself — a fairly\n  unusual thing to do)\n- `Proxy` objects (if this would be useful to you, log an issue and we'll chat)\n- Linking (e.g. one item in the store that is a reference to another item in the\n  store)\n\nYou can even store components in the store if you feel the need. This hasn't\nbeen performance tested, so proceed with caution.\n\n```jsx harmony\nconst Page = collect(({ store }) =\u003e {\n  const { Header, Footer, Button } = store.components;\n\n  return (\n    \u003cReact.Fragment\u003e\n      \u003cHeader title=\"Page one\" /\u003e\n\n      \u003cButton onClick={doSomething} /\u003e\n\n      \u003cFooter /\u003e\n    \u003c/React.Fragment\u003e\n  );\n});\n```\n\n### Map and Set limitations\n\nUpdating an object _key_ of a map entry will not always trigger a render of\ncomponents using that object. But in most cases you'd be storing your data in\nthe _value_ of a map entry, and that works fine.\n\nSimilarly, updating an object in a set may not trigger an update to components\nusing that object (adding/removing items from a set works fine).\n\n## When will my components be re-rendered?\n\nShort version: when they need to be, don't worry about it.\n\nLonger version: if a _property_ is changed (e.g.\n`store.page.title = 'Page two'`), any component that read that property when it\nlast rendered will be updated. If an object, array, map or set is changed (e.g.\n`store.tasks.pop()`) any component that read that object/array/map/set will be\nupdated.\n\nCheck out [tests/integration/updating](tests/integration/updating.test.tsx) for\nthe full suite of scenarios.\n\n## How many components should I wrap in `collect`?\n\nYou can wrap every component in `collect` if you feel like it. As a general\nrule, the more you wrap in `collect`, the fewer unnecessary renders you'll get,\nand the less you'll have to pass props down through your component tree.\n\nThere is one rule you must follow though: do not pass part of the store _into_ a\ncollected component as props. Don't worry if you're not sure what that means,\nyou'll get a development-time error if you try.\n[This issue explains why](https://github.com/davidgilbertson/react-recollect/issues/102).\n\nWhen dealing with components that are rendered as array items (e.g. `\u003cProduct\u003e`s\nin a `\u003cProductList\u003e`), you'll probably get the best performance with the\nfollowing setup:\n\n- Wrap the parent component in `collect`.\n- Don't wrap the child component in `collect`\n- Pass the required data to the child components as props.\n- Mark the child component as pure with `memo()` or `PureComponent`.\n\nWith this arrangement, when an item in the array changes (e.g. a product is\nstarred), Recollect will immutably update only that item in the store, and\ntrigger the parent component to update. React will skip the update on all the\nchildren that didn't change, so only the one child will re-render.\n\nFor a working example, see the\n[Recollect demo on CodeSandbox](https://codesandbox.io/s/lxy1mz200l).\n\n## Can I use this with class-based components and functional components?\n\nYep and yep.\n\n## Hooks?\n\nYep.\n\n## Will component state still work?\n\nYes, but be careful. If a change in state reveals some new UI, and a property\nfrom the store is only read in that UI (not elsewhere in the component) then\nRecollect won't be aware of it, and won't update your component if it changes.\n\nUse the [`useProps`](#usepropsproparray) function to make sure your component is\nsubscribed to changes in this property.\n\n## Do lifecycle methods still fire?\n\nYep. Recollect has no effect on `componentDidMount`, `componentDidUpdate` and\nfriends.\n\n### Why isn't my `componentDidUpdate` code firing?\n\nIf you have a store prop that you _only_ refer to in `componentDidUpdate` (e.g.\n`store.loaded`), then your component won't be subscribed to changes in that\nprop. So when `store.loaded` changes, your component might not be updated.\n\nUse the [`useProps`](#usepropsproparray) function to make sure your component is\nsubscribed to changes in this property.\n\n## Can I use this with `shouldComponentUpdate()`?\n\nYes, but no, but you probably don't need to.\n\nThe\n[React docs](https://reactjs.org/docs/react-component.html#shouldcomponentupdate)\nsay of `shouldComponentUpdate()`:\n\n\u003e This method only exists as a performance optimization. Do not rely on it to\n\u003e “prevent” a rendering, as this can lead to bugs ... In the future React may\n\u003e treat shouldComponentUpdate() as a hint rather than a strict directive, and\n\u003e returning false may still result in a re-rendering of the component\n\nSo, if you're using `shouldComponentUpdate` for _performance_ reasons, then you\ndon't need it anymore. If the `shouldComponentUpdate` method is executing, it's\nbecause Recollect has _told_ React to update the component, which means a value\nthat it needs to render has changed.\n\n## Can I wrap a `PureComponent` or `React.memo` in `collect`?\n\nThere's no need. The `collect` function wraps your component in a\n`PureComponent` and there's no benefit to having two of them.\n\nIt's a good idea to wrap _other_ components in `PureComponent` or `React.memo`\nthough — especially components that are rendered in an array, like `\u003cTodo\u003e`. If\nyou have a hundred todos, and add one to the list, you can skip a render for all\nthe existing `\u003cTodo\u003e` components if they're marked as pure.\n\n## Can I use this with `Context`?\n\nYes. Recollect doesn't interfere with other libraries that use `Context`.\n\nYou shouldn't need to use `Context` yourself though. You have a global `store`\nobject that you can read from and write to anywhere.\n\n## Can I use this with `ref`s?\n\nYes, refs just work, as long as you don't use the reserved name 'ref' (React\nstrips this out). You can use something like `inputRef` instead. For an example,\nsee [this test](tests/react/forwardRefFc.test.tsx)\n\n## Can I have multiple stores?\n\nNo. There is no performance improvement to be had, so the desire for multiple\nstores is just an organizational preference. For this, you can use 'selectors'\nto focus on a subset of your store.\n\n## Can I use Recollect without React?\n\nYes! You can use `store` without using `collect`. Pair this with `afterChange`\nto have an object that notifies you when its changed. For an example, check out\n[tests/integration/nodeJs.js](./tests/integration/nodeJs.js)\n\n## I'm getting a `no-param-reassign` ESLint error\n\nYou can add 'store' as a special case in your ESLint config so that the rule\nallows you to mutate the properties of store.\n\n```json\n{\n  \"rules\": {\n    \"no-param-reassign\": [\n      \"error\",\n      {\n        \"props\": true,\n        \"ignorePropertyModificationsFor\": [\"store\"]\n      }\n    ]\n  }\n}\n```\n\nCheck out the `no-param-reassign` rule in this repo's\n[eslint config](./.eslintrc.json) for the syntax.\n\n## Tell me about your tests\n\n- There's 100+ integration/unit tests in the [tests](./tests) directory.\n- There's a `/demo` directory with a Create React App site using Recollect. This\n  has a Cypress test suite.\n- There's [/demo/public/browser.html](./demo/public/browser.html) for manual\n  testing of the UMD build of Recollect.\n\n## How big is it?\n\n3—5 KB, depending on what else you've got installed. If you're coming from Redux\nland, you'll save about 1 KB in library size, but the big savings come from\ngetting rid of all your reducers.\n\n## Is reading/writing via a proxy slow?\n\nSlow, no. Slower than vanilla object operations, yes.\n\nLet's quantify with a case study: in an app that has a store with ~80,000\nproperties, ~30,000 of them proxied objects and ~1,000 component listeners,\nupdating a chunk of data requiring 50 new proxies takes ~2 milliseconds (on\ndesktop). For that app, 2ms was considered insignificant compared to the ~90ms\nspent on the resulting render cycle.\n\nIf you're processing big data and facing performance troubles, open an issue and\nwe'll chat.\n\n# Dependencies\n\nRecollect has a peer dependency of React `\u003e=15.3`.\n\n# Alternatives\n\nIf you want IE support, use Redux.\n\nIf you want explicit 'observables' and multiple stores, use MobX.\n\nIf you want a walk down memory lane, use Flux.\n\nAlso there is a library that is very similar to this one (I didn't copy,\npromise) called\n[`react-easy-state`](https://github.com/solkimicreb/react-easy-state).\n\n# Is it really OK to drop support for IE?\n\nSure, why not! Imagine: all that time you spend getting stuff to work for a few\nusers in crappy old browsers could instead be spent making awesome new features\nfor the vast majority of your users.\n\nFor inspiration, these brave websites have dropped the hammer and dropped\nsupport for IE:\n\n- GitHub (owned by Microsoft!)\n- devdocs.io\n- Flickr\n- Codepen\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavidgilbertson%2Freact-recollect","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdavidgilbertson%2Freact-recollect","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavidgilbertson%2Freact-recollect/lists"}