Skip to content
Myr

readme.md

This file

Path

readme.md

679 lines · 26.8 KiB · Markdown

Last changed by

Less is moreMichel Weststratebefore adoption1802421

History of this file

Take it

Picked a logoMichel Weststratebefore adoptionf1ca2f6

lines 1–2why, one step back
1<img src="images/immer-logo.png" height="200px" align="right"/>
2

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 3–4why, one step back
3# Immer
4

Merge pull request #156 from styfle/patch-1Michel Weststratebefore adoptione0a8a1a

line 5why, one step back
5[![npm](https://img.shields.io/npm/v/immer.svg)](https://www.npmjs.com/package/immer) [![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js) [![install size](https://packagephobia.now.sh/badge?p=immer)](https://packagephobia.now.sh/result?p=immer) [![Build Status](https://travis-ci.org/mweststrate/immer.svg?branch=master)](https://travis-ci.org/mweststrate/immer) [![Coverage Status](https://coveralls.io/repos/github/mweststrate/immer/badge.svg?branch=master)](https://coveralls.io/github/mweststrate/immer?branch=master) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/michelweststrate)

Picked a logoMichel Weststratebefore adoptionf1ca2f6

line 6why, one step back
6

Updated changelogMichel Weststratebefore adoption8f44348

line 7why, one step back
7_Create the next immutable state tree by simply modifying the current tree_

Doc improvementsMichel Weststratebefore adoptiona3fcf04

line 8why, one step back
8

More readme linksMichel Weststratebefore adoptiond4a165b

line 9why, one step back
9Did Immer make a difference to your project? Consider buying me a coffee!<br/><a href="https://www.buymeacoffee.com/mweststrate" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: auto !important;width: auto !important;" ></a>

added some readme clarificationsMichel Weststratebefore adoption897c284

line 10why, one step back
10

Doc improvementsMichel Weststratebefore adoptiona3fcf04

lines 11–12why, one step back
11---
12

Merge pull request #123 from styfle/patch-1benbraoubefore adoption02fe6b1

lines 13–15why, one step back
13* NPM: `npm install immer`
14* Yarn: `yarn add immer`15* CDN: Exposed global is `immer`

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 16–17why, one step back
16 * Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`
17 * JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`

Readme improvementsMichel Weststratebefore adoptiondcedda8

line 18why, one step back
18

Updated readme linksMichel Weststratebefore adoption553b6ce

lines 19–20why, one step back
19---
20

Object.is for equality, more tests. Fixes #43, #42, #48Michel Weststratebefore adoptione29a792

line 21why, one step back
21* Egghead lesson covering all of immer (7m): [Simplify creating immutable data trees with Immer](https://egghead.io/lessons/redux-simplify-creating-immutable-data-trees-with-immer)

Updated readme linksMichel Weststratebefore adoption553b6ce

line 22why, one step back
22* Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)

Added React Finland talk linkMichel Weststratebefore adoption899b53f

line 23why, one step back
23* [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate

added some readme clarificationsMichel Weststratebefore adoption897c284

lines 24–25why, one step back
24* Blog: by Workday Prism on why they picked Immer to manage immutable state [The Search for a Strongly-Typed, Immutable State](https://medium.com/workday-engineering/workday-prism-analytics-the-search-for-a-strongly-typed-immutable-state-a09f6768b2b5)
25* Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)

More readme linksMichel Weststratebefore adoptiond4a165b

line 26why, one step back
26* Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)

Updated readme linksMichel Weststratebefore adoption553b6ce

line 27why, one step back
27

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 28why, one step back
28Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way. It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 29why, one step back
29

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 30why, one step back
30The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_. Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state. This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 31why, one step back
31

Merge pull request #56 from jkhedani/masterMichel Weststratebefore adoption076fbd6

line 32why, one step back
32![immer-hd.png](images/hd/immer.png)

Doc improvementsMichel Weststratebefore adoptiona3fcf04

line 33why, one step back
33

`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea

line 34why, one step back
34Using 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).

Readme improvementsMichel Weststratebefore adoption58e9b57

line 35why, one step back
35

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 36why, one step back
36A 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.

Doc improvementsMichel Weststratebefore adoptiona3fcf04

lines 37–39why, one step back
37
38## API39

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 40why, one step back
40The Immer package exposes a default function that does all the work.

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 41why, one step back
41

`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea

line 42why, one step back
42`produce(currentState, producer: (draftState) => void): nextState`

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 43why, one step back
43

Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496

line 44why, one step back
44There is also a curried overload that is explained [below](#currying).

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 45why, one step back
45

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 46–48why, one step back
46## Example
4748```javascript

`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea

line 49why, one step back
49import produce from "immer"

Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb

line 50why, one step back
50

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 51–56why, one step back
51const baseState = [
52 {53 todo: "Learn typescript",54 done: true55 },56 {

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 57why, one step back
57 todo: "Try immer",

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 58–61why, one step back
58 done: false
59 }60]61

`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea

line 62why, one step back
62const nextState = produce(baseState, draftState => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 63why, one step back
63 draftState.push({todo: "Tweet about it"})

Doc improvementsMichel Weststratebefore adoptiona3fcf04

line 64why, one step back
64 draftState[1].done = true

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 65–67why, one step back
65})
66```67

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 68why, one step back
68The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 69–84why, one step back
69
70```javascript71// the new item is only added to the next state,72// base state is unmodified73expect(baseState.length).toBe(2)74expect(nextState.length).toBe(3)7576// same for the changed 'done' prop77expect(baseState[1].done).toBe(false)78expect(nextState[1].done).toBe(true)7980// unchanged data is structurally shared81expect(nextState[0]).toBe(baseState[0])82// changed data not (dûh)83expect(nextState[1]).not.toBe(baseState[1])84```

Doc improvementsMichel Weststratebefore adoptiona3fcf04

lines 85–87why, one step back
85
86## Benefits87

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

lines 88–93why, one step back
88* Immutability with normal JavaScript objects and arrays. No new APIs to learn!
89* Strongly typed, no string based paths selectors etc.90* Structural sharing out of the box91* Object freezing out of the box92* Deep updates are a breeze93* Boilerplate reduction. Less noise, more concise code.

Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0

line 94why, one step back
94* Small: bundled and minified: 2KB.

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 95why, one step back
95

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 96why, one step back
96Read further to see all these benefits explained.

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

line 97why, one step back
97

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 98–99why, one step back
98## Reducer Example
99

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 100why, one step back
100Here is a simple example of the difference that Immer could make in practice.

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 101–102why, one step back
101
102```javascript

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

lines 103–105why, one step back
103// Redux reducer
104// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js105const byId = (state, action) => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 106–117why, one step back
106 switch (action.type) {
107 case RECEIVE_PRODUCTS:108 return {109 ...state,110 ...action.products.reduce((obj, product) => {111 obj[product.id] = product112 return obj113 }, {})114 }115 default:116 return state117 }

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 118–120why, one step back
118}
119```120

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 121why, one step back
121After using Immer, that simply becomes:

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 122–123why, one step back
122
123```javascript

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 124why, one step back
124import produce from "immer"

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 125why, one step back
125

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 126why, one step back
126const byId = (state, action) =>

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 127–134why, one step back
127 produce(state, draft => {
128 switch (action.type) {129 case RECEIVE_PRODUCTS:130 action.products.forEach(product => {131 draft[product.id] = product132 })133 }134 })

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 135–136why, one step back
135```
136

transpile es5 codeMichel Weststratebefore adoptionf012154

line 137why, one step back
137Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 138why, one step back
138

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 139why, one step back
139Creating Redux reducer 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).

transpile es5 codeMichel Weststratebefore adoptionf012154

line 140why, one step back
140

Merge pull request #114 from xaviergonz/patch-1Michel Weststratebefore adoptionc71b173

line 141why, one step back
141_Note: it might be tempting after using producers for a while, to just place `produce` in your root reducer and then pass the draft to each reducer and work directly over such draft. 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._

Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b

line 142why, one step back
142

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

lines 143–144why, one step back
143## React.setState example
144

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 145why, one step back
145Deep updates in the state of React components can be greatly simplified as well by using immer. Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

lines 146–151why, one step back
146
147```javascript148/**149 * Classic React.setState with a deep merge150 */151onBirthDayClick1 = () => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 152why, one step back
152 this.setState(prevState => ({

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

line 153why, one step back
153 user: {

Merge pull request #104 from mikollo/patch-1Michel Weststratebefore adoptionc047a59

lines 154–155why, one step back
154 ...prevState.user,
155 age: prevState.user.age + 1

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

line 156why, one step back
156 }

Merge pull request #104 from mikollo/patch-1Michel Weststratebefore adoptionc047a59

line 157why, one step back
157 }))

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

lines 158–161why, one step back
158}
159160/**161 * ...But, since setState accepts functions,

Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd

line 162why, one step back
162 * we can just create a curried producer and further simplify!

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 163why, one step back
163 */

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

line 164why, one step back
164onBirthDayClick2 = () => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 165–169why, one step back
165 this.setState(
166 produce(draft => {167 draft.user.age += 1168 })169 )

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

lines 170–172why, one step back
170}
171```172

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

lines 173–174why, one step back
173## Currying
174

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 175why, one step back
175Passing a function as the first argument to `produce` 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. The producer function gets passed in the draft, and any further arguments that were passed to the curried function.

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

lines 176–192why, one step back
176
177For example:178179```javascript180// mapper will be of signature (state, index) => state181const mapper = produce((draft, index) => {182 draft.index = index183})184185// example usage186console.dir([{}, {}, {}].map(mapper))187//[{index: 0}, {index: 1}, {index: 2}])188```189190This mechanism can also nicely be leveraged to further simplify our example reducer:191192```javascript

Fixed configurability of array.length on proxies. Fixes #50Michel Weststratebefore adoption1c7df26

lines 193–194why, one step back
193import produce from 'immer'
194

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

lines 195–197why, one step back
195const byId = produce((draft, action) => {
196 switch (action.type) {197 case RECEIVE_PRODUCTS:

Merge pull request #71 from Keysox/patch-1Michel Weststratebefore adoptiond47db4d

line 198why, one step back
198 action.products.forEach(product => {

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 199why, one step back
199 draft[product.id] = product

Merge pull request #71 from Keysox/patch-1Michel Weststratebefore adoptiond47db4d

line 200why, one step back
200 })

Readme improvementsMichel Weststratebefore adoptiondcedda8

line 201why, one step back
201 return

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

lines 202–208why, one step back
202 })
203 }204})205```206207Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).208

Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496

lines 209–211why, one step back
209If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:
210211```javascript

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 212why, one step back
212import produce from "immer"

Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496

line 213why, one step back
213

Readme improvementsMichel Weststratebefore adoptiondcedda8

line 214why, one step back
214const byId = produce(

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 215–225why, one step back
215 (draft, action) => {
216 switch (action.type) {217 case RECEIVE_PRODUCTS:218 action.products.forEach(product => {219 draft[product.id] = product220 })221 return222 }223 },224 {225 1: {id: 1, name: "product-1"}

Readme improvementsMichel Weststratebefore adoptiondcedda8

lines 226–227why, one step back
226 }
227)

Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496

lines 228–229why, one step back
228```
229

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 230–233why, one step back
230## Patches
231232During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer.233This is a very powerful tool if you want to fork your state temporarily, and replay the changes to the original.

Update readmeMichel Weststratebefore adoption341cfeb

lines 234–239why, one step back
234
235Patches are useful in few scenarios:236 * To exchange incremental updates with other parties, for example over websockets237 * For debugging / traces, to see precisely how state is changed over time238 * As basis for undo/redo or as approach to replay changes on a slightly different state tree239

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 240–298why, one step back
240To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used
241to record the incremental updates and (inverse) apply them:242243```javascript244import produce, {applyPatches} from "immer"245246let state = {247 name: "Micheal",248 age: 32249}250251// Let's assume the user is in a wizard, and we don't know whether252// his changes should be end up in the base state ultimately or not...253let fork = state254// all the changes the user made in the wizard255let changes = []256// the inverse of all the changes made in the wizard257let inverseChanges = []258259fork = produce(260 fork,261 draft => {262 draft.age = 33263 },264 // The third argument to produce is a callback to which the patches will be fed265 (patches, inversePatches) => {266 changes.push(...patches)267 inverseChanges.push(...inversePatches)268 }269)270271// In the mean time, our original state is replaced, as, for example,272// some changes were received from the server273state = produce(state, draft => {274 draft.name = "Michel"275})276277// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!278state = applyPatches(state, changes)279280// state now contains the changes from both code paths!281expect(state).toEqual({282 name: "Michel", // changed by the server283 age: 33 // changed by the wizard284})285286// Finally, even after finishing the wizard, the user might change his mind and undo his changes...287state = applyPatches(state, inverseChanges)288expect(state).toEqual({289 name: "Michel", // Not reverted290 age: 32 // Reverted291})292```293294The generated patches are similar (but not the same) to the [RFC-6902 JSON patch standard](http://tools.ietf.org/html/rfc6902), except that the `path` property is an array, rather than a string.295This makes processing patches easier. If you want to normalize to the official specification, `patch.path = patch.path.join("/")` should do the trick. Anyway, this is what a bunch of patches and their inverse could look like:296297```json298[

syntax fixesMichel Weststratebefore adoptioncdaec5a

line 299why, one step back
299 { "op": "replace", "path": ["profile"], "value": { "name": "Veria", "age": 5 }},

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 300–305why, one step back
300 { "op": "remove", "path": ["tags", 3] }
301]302```303304```json305[

syntax fixesMichel Weststratebefore adoptioncdaec5a

line 306why, one step back
306 { "op": "replace", "path": ["profile"], "value": { "name": "Noa", "age": 6 }},

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 307–310why, one step back
307 { "op": "add", "path": ["tags", 3], "value": "kiddo"},
308]309```310

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

lines 311–312why, one step back
311## Auto freezing
312

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 313why, one step back
313Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default it is turned on during local development, and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 314why, one step back
314

Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd

lines 315–316why, one step back
315## Returning data from producers
316

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 317why, one step back
317It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway. However, it is allowed to just `return draft`.

Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd

line 318why, one step back
318

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 319why, one step back
319It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft. This can be useful to produce an entirely new state. Some examples:

Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd

lines 320–322why, one step back
320
321```javascript322const userReducer = produce((draft, action) => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 323–352why, one step back
323 switch (action.type) {
324 case "renameUser":325 // OK: we modify the current state326 draft.users[action.payload.id].name = action.payload.name327 return draft // same as just 'return'328 case "loadUsers":329 // OK: we return an entirely new state330 return action.payload331 case "adduser-1":332 // NOT OK: This doesn't do change the draft nor return a new state!333 // It doesn't modify the draft (it just redeclares it)334 // In fact, this just doesn't do anything at all335 draft = {users: [...draft.users, action.payload]}336 return337 case "adduser-2":338 // NOT OK: modifying draft *and* returning a new state339 draft.userCount += 1340 return {users: [...draft.users, action.payload]}341 case "adduser-3":342 // OK: returning a new state. But, unnecessary complex and expensive343 return {344 userCount: draft.userCount + 1,345 users: [...draft.users, action.payload]346 }347 case "adduser-4":348 // OK: the immer way349 draft.userCount += 1350 draft.users.push(action.payload)351 return352 }

Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd

lines 353–355why, one step back
353})
354```355

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

line 356why, one step back
356_Note: It is not possible to return `undefined` this way, as it is indistiguishable from *not* updating the draft! Read on..._

added some readme clarificationsMichel Weststratebefore adoption897c284

line 357why, one step back
357

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

lines 358–390why, one step back
358## Producing `undefined` using `nothing`
359360So, in general one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft.361There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:362363```javascript364produce({}, draft => {365 // don't do anything366})367```368369Versus:370371```javascript372produce({}, draft => {373 // Try to return undefined from the producer374 return undefined375})376```377378The problem is that in JavaScript a function that doesn't return anything, also returns `undefined`!379So immer cannot differentiate between those different cases.380So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.381382However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:383384```javascript385import produce, { nothing } from "immer"386387const state = {388 hello: "world"389}390

Less is moreMichel Weststratebefore adoption1802421

line 391why, one step back
391produce(state, (draft) => {})

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

line 392why, one step back
392produce(state, (draft) => undefined)

Less is moreMichel Weststratebefore adoption1802421

line 393why, one step back
393// Both return the original state: { hello: "world"}

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

lines 394–400why, one step back
394
395produce(state, (draft) => nothing)396// Produces a new state, 'undefined'397```398399N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.400

Merge pull request #179 from RichieAHB/rahb/add-originalMichel Weststratebefore adoptionf8479c2

lines 401–411why, one step back
401## Extracting the original object from a proxied instance
402403Immer exposes a named export `original` that will get the original object from the proxied instance inside `produce` (or return `undefined` for unproxied values). A good example of when this can be useful is when searching for nodes in a tree-like state using strict equality.404405```js406const baseState = { users: [{ name: "Richie" }] };407const nextState = produce(baseState, draftState => {408 original(draftState.users) // is === baseState.users409})410```411

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

lines 412–418why, one step back
412## Using `this`
413414The recipe will be always invoked with the `draft` as `this` context.415416This means that the following constructions are also valid:417418```javascript

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 419why, one step back
419const base = {counter: 0}

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

lines 420–421why, one step back
420
421const next = produce(base, function() {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 422why, one step back
422 this.counter++

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

lines 423–427why, one step back
423})
424console.log(next.counter) // 1425426// OR427const increment = produce(function() {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 428why, one step back
428 this.counter++

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

lines 429–432why, one step back
429})
430console.log(increment(base).counter) // 1431```432

Merge pull request #183 from drcmda/patch-1Michel Weststratebefore adoption4b9a7d3

lines 433–434why, one step back
433## Inline shortcuts using `void`
434

Be explicit about not supporting arbitrary properties on arraysMichel Weststratebefore adoption0a80c2c

line 435why, one step back
435Draft mutations in Immer usually warrant a code block, since a return denotes an overwrite. Sometimes that can stretch code a little more than you might be comfortable with.

Merge pull request #183 from drcmda/patch-1Michel Weststratebefore adoption4b9a7d3

lines 436–446why, one step back
436
437In such cases you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.438439```javascript440// Single mutation441produce(draft => void (draft.user.age += 1))442443// Multiple mutations444produce(draft => void (draft.user.age += 1, draft.user.height = 186))445```446

Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69

line 447why, one step back
447Code style is highly personal, but for code bases that are to be understood by many, we recommend to stick to the classic `draft => { draft.user.age += 1}` to avoid cognitive overhead.

Be explicit about not supporting arbitrary properties on arraysMichel Weststratebefore adoption0a80c2c

line 448why, one step back
448

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

lines 449–452why, one step back
449## TypeScript or Flow
450451The Immer package ships with type definitions inside the package, which should be picked up by TypeScript and Flow out of the box and without further configuration.452

Merge pull request #161 from knpwrs/mapped-draft-typeMichel Weststratebefore adoptionedc8b7c

lines 453–455why, one step back
453The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:
454455```ts

Merge pull request #190 from aretecode/patch-1Michel Weststratebefore adoptiond0ac0e6

line 456why, one step back
456import produce from 'immer'

Merge pull request #161 from knpwrs/mapped-draft-typeMichel Weststratebefore adoptionedc8b7c

lines 457–458why, one step back
457
458interface State {

Merge pull request #190 from aretecode/patch-1Michel Weststratebefore adoptiond0ac0e6

line 459why, one step back
459 readonly x: number

Merge pull request #161 from knpwrs/mapped-draft-typeMichel Weststratebefore adoptionedc8b7c

lines 460–463why, one step back
460}
461462// `x` cannot be modified here463const state: State = {

Merge pull request #190 from aretecode/patch-1Michel Weststratebefore adoptiond0ac0e6

lines 464–465why, one step back
464 x: 0
465}

Merge pull request #161 from knpwrs/mapped-draft-typeMichel Weststratebefore adoptionedc8b7c

line 466why, one step back
466

Merge pull request #170 from knpwrs/patch-2Michel Weststratebefore adoptionb618bf9

line 467why, one step back
467const newState = produce<State>(state, draft => {

Merge pull request #161 from knpwrs/mapped-draft-typeMichel Weststratebefore adoptionedc8b7c

line 468why, one step back
468 // `x` can be modified here

Merge pull request #190 from aretecode/patch-1Michel Weststratebefore adoptiond0ac0e6

lines 469–470why, one step back
469 draft.x++
470})

Merge pull request #161 from knpwrs/mapped-draft-typeMichel Weststratebefore adoptionedc8b7c

lines 471–476why, one step back
471
472// `newState.x` cannot be modified here473```474475This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!476

Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0

line 477why, one step back
477## Immer on older JavaScript environments?

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 478why, one step back
478

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 479why, one step back
479By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 480why, one step back
480

`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015

lines 481–496why, one step back
481## Importing immer
482483`produce` is exposed as the default export, but optionally it can be used as name import as well, as this benefits some older project setups. So the following imports are all correct, where the first is recommend:484485```javascript486import produce from "immer"487import { produce } from "immer"488489const { produce } = require("immer")490const produce = require("immer").produce491const produce = require("immer").default492493import unleashTheMagic from "immer"494import { produce as unleashTheMagic } from "immer"495```496

Improved the readme concerning limitations. Fixes #185Michel Weststratebefore adoptionf0e8c47

line 497why, one step back
497## Limitations

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 498why, one step back
498

Improved the readme concerning limitations. Fixes #185Michel Weststratebefore adoptionf0e8c47

lines 499–508why, one step back
499Immer supports the following types of data:
5001. All kinds of primitive values5011. `Date` instances, but: only if not mutated, see below5021. Arrays, but: non-standard attributes are not supported (like: `array.test = "Test"`)5031. Plain objects (objects that have as prototype either `null` or `Object`)5041. Functions, assuming they aren't mutated5051. Other value types (like class instances) can be stored in the tree, but note that Immer won't work _inside_ those objects. In other words, if you modify a class instance, this will _not_ result in clone and unmodified original, but just in a modified original.506507# Pitfalls508

Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd

line 509why, one step back
5091. Don't redefine draft like, `draft = myCoolNewState`. Instead, either modify the `draft` or return a new state. See [Returning data from producers](#returning-data-from-producers).

Improved the readme concerning limitations. Fixes #185Michel Weststratebefore adoptionf0e8c47

lines 510–511why, one step back
5101. Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, and there should be no circular references.
5111. Class instances are not, and will not supported first-class supported. Read [here](https://github.com/mweststrate/immer/issues/155#issuecomment-407725592) why classes are a conceptual mismatch (and technically extremely challenging)

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 512why, one step back
5121. For example, working with `Date` objects is no problem, just make sure you never modify them (by using methods like `setYear` on an existing instance). Instead, always create fresh `Date` instances. Which is probably what you were unconsciously doing already.

Improved the readme concerning limitations. Fixes #185Michel Weststratebefore adoptionf0e8c47

line 513why, one step back
5131. 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`. Also realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 514why, one step back
5141. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.

Merge pull request #192 from TomFaulkner/patch-1Michel Weststratebefore adoption1401c08

line 515why, one step back
5151. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

line 516why, one step back
5161. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistiguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.

Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56

lines 517–556why, one step back
5171. Immer does not support built in data-structures like `Map` and `Set`. However, it is fine to just immutably "update" them yourself but still leverage immer wherever possible:
518519```javascript520const state = {521 title: "hello",522 tokenSet: new Set()523}524525const nextState = produce(state, draft => {526 draft.title = draft.title.toUpperCase() // let immer do it's job527 // don't use the operations onSet, as that mutates the instance!528 // draft.tokenSet.add("c1342")529530 // instead: clone the set (once!)531 const newSet = new Set(draft.tokenSet)532 // mutate the clone (just in this producer)533 newSet.add("c1342")534 // update the draft with the new set535 draft.tokenSet = newSet536})537```538539Or a deep update in maps (well, don't use maps for this use case, but as example):540541```javascript542const state = {543 users: new Map(["michel", { name: "miche" }])544}545546const nextState = produce(state, draft => {547 const newUsers = new Map(draft.users)548 // mutate the new map and set a _new_ user object549 // but leverage produce again to base the new user object on the original one550 newUsers.set("michel", produce(draft.users.get("michel"), draft => {551 draft.name = "michel"552 }))553 draft.users = newUsers554})555```556

Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff

line 557why, one step back
557

Added section with cool stuffMichel Weststratebefore adoption69aedd8

lines 558–559why, one step back
558## Cool things built with immer
559

Updated who uses sectionMichel Weststratebefore adoption0152244

line 560why, one step back
560* [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_

Readme improvementsMichel Weststratebefore adoptiondcedda8

line 561why, one step back
561* [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_

Added section with cool stuffMichel Weststratebefore adoption69aedd8

lines 562–563why, one step back
562* [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_
563* [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_

Merge pull request #122 from jeffreyyoung/patch-1Michel Weststratebefore adoption1b381ff

line 564why, one step back
564* [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux developement quicker and easier_

Updated who uses sectionMichel Weststratebefore adoption0152244

line 565why, one step back
565* [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

line 566why, one step back
566* [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_

Merge pull request #191 from neurosnap/patch-1Michel Weststratebefore adoption2d8f8f4

line 567why, one step back
567* [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate

Updated who uses sectionMichel Weststratebefore adoption0152244

line 568why, one step back
568* ... and [many more](https://www.npmjs.com/browse/depended/immer)

Added section with cool stuffMichel Weststratebefore adoption69aedd8

line 569why, one step back
569

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

lines 570–571why, one step back
570## How does Immer work?
571

Object.is for equality, more tests. Fixes #43, #42, #48Michel Weststratebefore adoptione29a792

line 572why, one step back
572Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

line 573why, one step back
573

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 574–577why, one step back
574## Example patterns.
575576_For those who have to go back to thinking in object updates :-)_577

Merge pull request #124 from capaj/patch-1benbraoubefore adoptionbbedb9f

line 578why, one step back
578```javascript

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 579why, one step back
579import produce from "immer"

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 580–582why, one step back
580
581// object mutations582const todosObj = {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 583–585why, one step back
583 id1: {done: false, body: "Take out the trash"},
584 id2: {done: false, body: "Check Email"}585}

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 586–588why, one step back
586
587// add588const addedTodosObj = produce(todosObj, draft => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 589–590why, one step back
589 draft["id3"] = {done: false, body: "Buy bananas"}
590})

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 591–593why, one step back
591
592// delete593const deletedTodosObj = produce(todosObj, draft => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 594–595why, one step back
594 delete draft["id1"]
595})

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 596–598why, one step back
596
597// update598const updatedTodosObj = produce(todosObj, draft => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 599–600why, one step back
599 draft["id1"].done = true
600})

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 601–603why, one step back
601
602// array mutations603const todosArray = [

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 604–606why, one step back
604 {id: "id1", done: false, body: "Take out the trash"},
605 {id: "id2", done: false, body: "Check Email"}606]

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 607–609why, one step back
607
608// add609const addedTodosArray = produce(todosArray, draft => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 610–611why, one step back
610 draft.push({id: "id3", done: false, body: "Buy bananas"})
611})

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 612–614why, one step back
612
613// delete614const deletedTodosArray = produce(todosArray, draft => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 615–618why, one step back
615 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)
616 // or (slower):617 // return draft.filter(todo => todo.id !== "id1")618})

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 619–621why, one step back
619
620// update621const updatedTodosArray = produce(todosArray, draft => {

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

lines 622–623why, one step back
622 draft[draft.findIndex(todo => todo.id === "id1")].done = true
623})

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 624–625why, one step back
624```
625

Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff

lines 626–627why, one step back
626## Performance
627

Update readmeMichel Weststratebefore adoption341cfeb

line 628why, one step back
628Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 50,000 todo items, and updates 5,000 of them. _Freeze_ indicates that the state tree has been frozen after producing it. This is a _development_ best practice, as it prevents developers from accidentally modifying the state tree.

Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff

line 629why, one step back
629

Update readmeMichel Weststratebefore adoption341cfeb

line 630why, one step back
630These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.

Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff

line 631why, one step back
631

Fixed performance imagesMichel Weststratebefore adoption89e0d24

line 632why, one step back
632![performance.png](images/performance.png)

Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff

line 633why, one step back
633

Update readmeMichel Weststratebefore adoption341cfeb

line 634why, one step back
634Most important observation:

Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b

line 635why, one step back
635

Merge pull request #193 from TomFaulkner/patch-2Michel Weststratebefore adoption00a7720

line 636why, one step back
636* Immer with proxies is roughly speaking twice to three times slower as a hand written reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.

Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff

line 637why, one step back
637* Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)

Update readmeMichel Weststratebefore adoption341cfeb

lines 638–639why, one step back
638* Generating patches doesn't significantly slow immer down
639* The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.

Added performance measurements, fixes #6Michel Weststratebefore adoption553299f

line 640why, one step back
640

Added FAQ sectionMichel Weststratebefore adoptionb9b418e

lines 641–668why, one step back
641## FAQ
642643_(for those who skimmed the above instead of actually reading)_644645**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**646647A: Yes648649**Q: Does Immer support deep updates?**650651A: Yes652653**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**654655A: Yes656657**Q: Can I typecheck my data structures when using Immer?**658659A: Yes660661**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**662663A: Yes664665**Q: Is it fast?**666667A: Yes668

Added question about freezingMichel Weststratebefore adoption6ac7707

lines 669–672why, one step back
669**Q: Idea! Can Immer freeze the state for me?**
670671A: Yes672

Added performance measurements, fixes #6Michel Weststratebefore adoption553299f

lines 673–675why, one step back
673## Credits
674675Special 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.

Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e

lines 676–679why, one step back
676
677## Donations678679A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)