{"id":17135373,"url":"https://github.com/joaogranado/react-updater","last_synced_at":"2025-04-13T09:05:46.253Z","repository":{"id":57347012,"uuid":"90068189","full_name":"joaogranado/react-updater","owner":"joaogranado","description":"Functional stateful components made easy","archived":false,"fork":false,"pushed_at":"2020-06-02T18:24:42.000Z","size":3281,"stargazers_count":9,"open_issues_count":19,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-13T09:05:30.162Z","etag":null,"topics":["functional","higher-order-component","reactjs","state","stateful"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","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/joaogranado.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":"2017-05-02T19:03:35.000Z","updated_at":"2023-10-17T08:53:04.000Z","dependencies_parsed_at":"2022-09-17T23:01:50.799Z","dependency_job_id":null,"html_url":"https://github.com/joaogranado/react-updater","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joaogranado%2Freact-updater","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joaogranado%2Freact-updater/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joaogranado%2Freact-updater/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joaogranado%2Freact-updater/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/joaogranado","download_url":"https://codeload.github.com/joaogranado/react-updater/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248688574,"owners_count":21145766,"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":["functional","higher-order-component","reactjs","state","stateful"],"created_at":"2024-10-14T19:47:24.895Z","updated_at":"2025-04-13T09:05:46.214Z","avatar_url":"https://github.com/joaogranado.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# React Updater\n\n\u003e Functional stateful components made easy\n\nReact Updater is a Higher-order Component that provides a state updater function and enforces best practices regarding state management in your React applications.\n\n## Status\n\n[![Travis](https://img.shields.io/travis/joaogranado/react-updater.svg)](https://travis-ci.org/joaogranado/react-updater)\n[![Greenkeeper badge](https://badges.greenkeeper.io/joaogranado/react-updater.svg)](https://greenkeeper.io/)\n\n## Installation\n\n```sh\nnpm install react-updater --save\n```\n\n```sh\nyarn add react-updater\n```\n\n## How It Works\n\nReact functional components are stateless so we need to use classes if we want to have local state. A simple solution to this is to delegate the state to an ancestor by creating an Higher-order Component to wrap the stateless component into a stateful component. The problem here is that if we return a new callback handler on subsequent renders we cannot guarantee reference equality, which can be a problem for components that rely on `props` equality.\n\nBy memoizing state updaters and additional parameters, React Updater guarantees the referential equality of the callback handlers across renders.\n\nIt also requires you to pass a function as state updater. This has some benefits: it ensures the state is always predictable across multiple calls of `setState()` and you can unit test complex state transitions without shallow render.\n\nSince in functional components you cannot access `this`, it provides you a way to attach `props` and other data to your state updaters without using closures.\n\nTo create a stateful functional component you just need to define the initial state, specify your state updaters and pass them to the `update()` function. That's it!\n\n```js\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport withUpdater from 'react-updater';\n\n// Initial state.\nconst state = 0;\n\n// State updaters.\nconst increment = (state, props, event) =\u003e state + props.step;\nconst decrement = (state, props, event) =\u003e state - props.step;\n\nconst Counter = (props) =\u003e (\n  \u003cdiv\u003e\n    \u003ch1\u003e{props.state}\u003c/h1\u003e\n    \u003cbutton onClick={props.update(decrement, props)}\u003e{'-'}\u003c/button\u003e\n    \u003cbutton onClick={props.update(increment, props)}\u003e{'+'}\u003c/button\u003e\n  \u003c/div\u003e\n);\n\nconst App = withUpdater(state)(Counter);\n\nReactDOM.render(\u003cApp step={1} /\u003e, document.getElementById('root'));\n```\n\n## API\n\n### `withUpdater()`\n\n```js\nwithUpdater(\n  initialState: any | (ownerProps: Object) =\u003e any\n): HigherOrderComponent\n```\n\nPasses three additional props to the base component: a state value, a `update` function to update that state value and a `handle` function which is a subset of the `update` but does not update the component.\n\n#### `update()`\n\n```js\nupdate(handler: Function, ...params): (...args): void\n```\n\nThis function wraps every callback handler. It takes a callback and returns a **memoized** callback that will give you the previous state, and additional arguments when the callback is called and ensures the state is updated after the callback.\n\n```js\nconst onClick = (state, increment) =\u003e state + increment;\nconst Component = props =\u003e \u003cdiv onClick={props.update(onClick, 1)} /\u003e;\n\nexport default withUpdater(0)(Component);\n```\n\nSince this wraps the callback handler in a `setState` call, the handler should always return a new state which can be an object or a single value.\n\n**Important:** `update` memoizes the given state updaters in order to avoid a common pitfall associated with components that rely on props equality by using `shouldComponentUpdate`. This can be avoided with the class syntax by using `this.onClick`, but if you pass inline functions as a state updater, `update()` will return a new callback handler. This can lead to de-optimizations because `shouldComponentUpdate` will return `true` on every render since `props.onClick !== nexProps.onClick`.\n\nIf you you register the same callback with different data multiple times, ince the `update()` function memoizes the state updater and attaches the additional data to the new callback handler, so the expected parameters will be the ones passed on the last call of `update()`. To avoid this limitation consider the following example:\n\n```js\n// If you click on the `#first` button the final state will be \"2\" instead of \"1\",\n// since the final value corresponds to the last call of `update()` for the same\n// state updater, so the `step` parameter will be \"2\".\nconst increment = (state, step) =\u003e state + step;\n\nwithUpdater(0)(props =\u003e (\n  \u003cdiv\u003e\n    \u003ch1\u003e{props.state}\u003c/h1\u003e\n    \u003cbutton id={'first'} onClick={props.update(increment, 1)} /\u003e\n    \u003cbutton id={'second'} onClick={props.update(increment, 2)} /\u003e\n  \u003c/div\u003e\n));\n\n// Instead do the following:\nconst increment = (state, step) =\u003e state + step;\nconst incrementOne = state =\u003e increment(state, 1);\nconst incrementTwo = state =\u003e increment(state, 2);\n\nwithUpdater(0)(props =\u003e (\n  \u003cdiv\u003e\n    \u003ch1\u003e{props.state}\u003c/h1\u003e\n    \u003cbutton id={'first'} onClick={props.update(incrementOne)} /\u003e\n    \u003cbutton id={'second'} onClick={props.update(incrementTwo)} /\u003e\n  \u003c/div\u003e\n));\n\n// However if the attached data has the same value it is ok to do the following:\nconst increment = (state, props) =\u003e state + props.step;\n\nwithUpdater(0)(props =\u003e (\n  \u003cdiv\u003e\n    \u003ch1\u003e{props.state}\u003c/h1\u003e\n    \u003cbutton id={'first'} onClick={props.update(increment, props)} /\u003e\n    \u003cbutton id={'second'} onClick={props.update(increment, props)} /\u003e\n  \u003c/div\u003e\n));\n```\n\n#### `handle()`\n\n```js\nhandle(handler: Function, ...params): (...args): Function\n```\n\nThis method is a convenient subset of `update()` but it does not update the state, so there is no need to return a new `state`. This allows passing `props` or other data to events without needing to use closures, while keeping the function referential identity.\n\n**Example:**\n\n```js\nconst setUsers = (state, users) =\u003e [...state, ...users];\nconst onClick = props =\u003e {\n  fetch('/users')\n    .then(response =\u003e response.json())\n    .then(props.update(setUsers));\n};\n\nconst Component = props =\u003e \u003cdiv onClick={props.handle(onClick, props)} /\u003e;\n\nexport default withUpdater()(Component);\n```\n\n#### `state`\nYou can pass any arbitrary value to the initial state and it will be handled accordingly. If you pass an object as the initial state, the updater will handle it according to the default `setState()` behavior. If you pass a function to the initial state it will be provided with the owner props that can be used to define the initial state.\n\n**Arbitrary value**\n\n```js\nconst state = 0;\nconst increment = state =\u003e state + 1;\nconst Counter = props =\u003e (\n  \u003cdiv\u003e\n    \u003cdiv\u003e{props.state}\u003c/div\u003e\n    \u003cbutton onClick={props.update(increment)}\u003e\n      {'+'}\n    \u003c/button\u003e\n  \u003c/div\u003e\n);\n\nexport default withUpdater(state)(Counter);\n```\n\n**Plain Object**\n\n```js\nconst state = { count: 0 };\nconst increment = state =\u003e ({ count: state.count + 1 });\nconst Counter = props =\u003e (\n  \u003cdiv\u003e\n    \u003cdiv\u003e{props.state.count}\u003c/div\u003e\n    \u003cbutton onClick={props.update(increment)}\u003e\n      {'+'}\n    \u003c/button\u003e\n  \u003c/div\u003e\n);\n\nexport default withUpdater(state)(Counter);\n```\n\n**Function**\n\n```js\n// ./counter.js\nconst state = props =\u003e props.initialValue;\nconst increment = state =\u003e state + 1;\nconst component = props =\u003e (\n  \u003cdiv\u003e\n    \u003cdiv\u003e{props.state}\u003c/div\u003e\n    \u003cbutton onClick={props.update(increment)}\u003e\n      {'+'}\n    \u003c/button\u003e\n  \u003c/div\u003e\n);\n\nexport default withUpdater(state)(Counter);\n\n// ./app.js\nimport Counter from './counter.js';\n\nconst App = () =\u003e \u003cCounter initialValue={0} /\u003e\n```\n\n### Bonus\n\n#### Implementing a reducer\n\nInstead of creating several callbacks to update the state we can use a reducer pattern to update the state based on redux-like action types.\n\n```js\nconst count = (state = 0, action) =\u003e {\n  switch (action) {\n    case 'DECREMENT':\n      return state - 1;\n    case 'INCREMENT':\n      return state + 1;\n    default:\n      return state;\n  }\n};\n\nconst increment = state =\u003e count(state, 'INCREMENT');\nconst decrement = state =\u003e count(state, 'DECREMENT');\n\nconst Counter = props =\u003e (\n  \u003cdiv\u003e\n    \u003cdiv\u003e{props.state}\u003c/div\u003e\n\n    \u003cbutton onClick={props.update(decrement)}\u003e\n      {'-'}\n    \u003c/button\u003e\n\n    \u003cbutton onClick={props.update(increment)}\u003e\n      {'+'}\n    \u003c/button\u003e\n  \u003c/div\u003e\n);\n\nexport default withUpdater(count())(Counter);\n```\n\n## References\nThis library takes some cues from to the [Reason-React](https://github.com/reasonml/reason-react) implementation of the state updater.\n\n## Licence\n\nMIT © [João Granado](https://github.com/joaogranado)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoaogranado%2Freact-updater","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjoaogranado%2Freact-updater","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoaogranado%2Freact-updater/lists"}