Skip to content
Myr

Gave the readme a sane order

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 4ec6076 · Browse files · 2 files+101 added−86 removed
This commit

State

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

Diff stats

2 files+101 added−86 removed

  • tests:+2 added−1 removed
  • other:+99 added−85 removed

2 files+101 added−86 removed

modified:__tests__/curry.js+2 added-1 removed
modified:readme.md+99 added-85 removed
3 unmodified lines
4[![Coverage Status](https://coveralls.io/repos/github/mweststrate/immer/badge.svg?branch=master)](https://coveralls.io/github/mweststrate/immer?branch=master)5[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)6[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://mobx.js.org/donate.html)788_Create the next immutable state tree by simply modifying the current tree_910---11
10 unmodified lines
22![immer.png](images/immer.png)2324Using immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).2527A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applicable to plain, native JavaScript data structures (arrays and objects) without further needing any library.26A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applied to plain, native JavaScript data structures (arrays and objects) without further needing any library.2728## Installation2930`npm install immer`3132## API3335The immer package exposes a single function:34The immer package exposes a default function that does all the work.3536`immer(currentState, fn: (draftState) => void): nextState`3738There is also a curried overload that is explained [below](#currying)3940## Example4142```javascript43import immer from "immer"
32 unmodified lines
76// changed data not (dûh)77expect(nextState[1]).not.toBe(baseState[1])78```7979## Using immer on older JavaScript environments8081By default `immer` tries to use proxies for optimal performance.82However, on older JavaScript engines `Proxy` is not available.83For example, Microsoft Internet Explorer or React Native on Android.84In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:8586```javascript87import immer from "immer/es5"88```8980## Benefits8192* Use the language© to construct create your next state93* Use JavaScript native arrays and object94* Automatic immutability; any state tree produced by `immer` will by defualt be deeply frozen95* Strongly typed, no string based paths etc96* Deep updates are trivial97* Small, dependency free library with minimal api surface98* No accidental mutations of current state, but intentional mutations of a draft state82* Immutability with normal JavaScript objects and arrays. No new APIs to learn!83* Strongly typed, no string based paths selectors etc.84* Structural sharing out of the box85* Object freezing out of the box86* Deep updates are a breeze87* Boilerplate reduction. Less noise, more concise code.88100## Auto freezing89Read further to see all these benefits explained.90102 Immer automatically freezes any state trees that are modified using `immer.103 This protects against accidental modifications of the state tree outside of an immer function.104 This comes with a performance impact, so it is recommended to disable this option in production.105 It is by default enabled.106107 Use `setAutoFreeze(true / false)` to turn this feature on or off.10891## Reducer Example92111Here is a simple example of the difference that this approach could make in practice.112The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)93Here is a simple example of the difference that Immer could make in practice.94114_Note, this is just a sample application of the `immer` package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_9596```javascript97// Redux reducer98// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js117const todo = (state, action) => {99const byId = (state, action) => {100 switch (action.type) {119 case 'ADD_TODO':101 case RECEIVE_PRODUCTS:102 return {121 id: action.id,122 text: action.text,123 completed: false124 }125 case 'TOGGLE_TODO':126 if (state.id !== action.id) {127 return state128 }129130 return {103 ...state,132 completed: !state.completed104 ...action.products.reduce((obj, product) => {105 obj[product.id] = product106 return obj107 }, {})108 }109 default:110 return state111 }112}138139const todos = (state = [], action) => {140 switch (action.type) {141 case 'ADD_TODO':142 return [143 ...state,144 todo(undefined, action)145 ]146 case 'TOGGLE_TODO':147 return state.map(t =>148 todo(t, action)149 )150 default:151 return state152 }153}113```114156After using immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):115After using immer, that simply becomes:116117```javascript118import immer from 'immer'119161const todos = (state = [], action) =>162 // immer produces nextState from draftState and returns it163 immer(state, draftState => {120const byId = (state, action) =>121 produce(state, draft => {122 switch (action.type) {165 case 'ADD_TODO':166 draftState.push({167 id: action.id,168 text: action.text,169 completed: false123 case RECEIVE_PRODUCTS:124 action.products.forEach(product => {125 draft[product.id] = product126 })171 return172 case 'TOGGLE_TODO':173 const todo = draftState.find(todo => todo.id === action.id)174 todo.completed = !todo.completed175 return127 }128 })129```130180Creating middleware or a reducer wrapper that applies `immer` automatically is left as exercise for the reader :-).131Note that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.132182---133_Note, creating Redux reducer is just a sample application of the `immer` package.134Immer is not just designed to simplify Redux reducers.135It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_136137## Currying138139`produce` can be called with one or two arguments.140The one argument version is intended to be used as currying. This means that you get a pre-pound producer, that only needs a state to produce the value from.141The producer function get's passed in the draft, and any further arguments that were passed to the curried function.142143For example:144145```javascript146// mapper will be of signature (state, index) => state147const mapper = produce((draft, index) => {148 draft.index = index149})150151// example usage152console.dir([{}, {}, {}].map(mapper))153//[{index: 0}, {index: 1}, {index: 2}])154```155156This mechanism can also nicely be leveraged to further simplify our example reducer:157158```javascript159160const byId = produce((draft, action) => {161 switch (action.type) {162 case RECEIVE_PRODUCTS:163 action.products.forEach(product => {164 draft[product.id] = product165 })166 }167})168```169170Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).171One think to keep in mind; you cannot use this construction to initialize an uninitialized state. E.g. `draft = {}` doesn't do anything useful.172173174## Auto freezing175176 Immer automatically freezes any state trees that are modified using `produce`.177 This protects against accidental modifications of the state tree outside of an immer function.178 This comes with a performance impact, so it is recommended to disable this option in production.179 It is by default enabled.180 Use `setAutoFreeze(true / false)` to turn this feature on or off.181182## Using immer on older JavaScript environments183184By default `immer` tries to use proxies for optimal performance.185However, on older JavaScript engines `Proxy` is not available.186For example, Microsoft Internet Explorer or React Native on Android.187In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:188189```javascript190import immer from "immer/es5"191```192193## More reducer examples194195Here are some typical reducer examples, take from the Redux [Immutable Update Patterns](https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) page, and their immer counter part.196These examples are semantically equivalent and produce the exact same state.197198```javascript
53 unmodified lines
252 })253}254```255245## Limitations256## Pitfalls257247* Currently, only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)248* Currently, only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)249250## Pitfalls:251258* Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.259* Immer only processes native arrays and plain objects (with a prototype of `null` or `Object`). Any other type of value will be treated verbatim! So if you modify a `Map` or `Buffer` or whatever complex object from the draft state, it will be that very same object in both the base state as the next state. In such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.253* Make sure to modify the draft state you get passed in in the callback function, not the original current state that was passed as the first argument to `immer`!254* Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the `immer` block or read from the `currentState` rather than the `draftState`260* Since immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`261* Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.262263## How does immer work?264265Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/9d73d8f71cb3).266267## Performance268269Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.270This test takes 100.000 todo items, and updates 10.000 of them.
14 unmodified lines
285286## Credits287288Special thanks goes to @Mendix, which supports it's employees to experiment completely freely two full days a month, which formed the kick-start for this project.289290## Donations291292A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)