Skip to content
Myr

Added `React.setState` example

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by Michel Weststrate · parent 2b6cf4f · Browse files · 1 file+29 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+29 added−0 removed

  • other:+29 added−0 removed

1 file+29 added−0 removed

modified:readme.md+29 added
135 unmodified lines
136It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).137138_Note: it might be tempting after using producers a while, to just put `produce` in your root reducer, and then past the draft along to each reducer and work on that. Don't do that. It kills the point of Redux where each reducer is testable as pure reducer. Immer is best used when applying it to small individual pieces of logic._139140## React.setState example141142Deep updates in the state of React components can be greatly simplified as well by using immer.143Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):144145```javascript146/**147 * Classic React.setState with a deep merge148 */149onBirthDayClick1 = () => {150 this.setState({151 user: {152 ...this.state.user,153 age: this.state.user.age + 1154 }155 })156}157158/**159 * ...But, since setState accepts functions,160 * we can just create curried producer and simplify this!161*/162onBirthDayClick2 = () => {163 this.setState(produce(draft => {164 draft.user.age += 1165 })166}167```168169## Currying170171`produce` can be called with one or two arguments.172The one argument version is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from.
151 unmodified lines