Skip to content
Myr

readme.md

This file

Path

readme.md

548 lines · 21.0 KiB · Markdown

Last changed by

Update readmeMichel Weststratebefore adoption341cfeb

History of this file

Take it

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 1–2why, one step back
1# Immer
2

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

line 3why, one step back
3[![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)

Merge pull request #25 from Gregjarvez/travisMichel Weststratebefore adoption55ec6d0

line 4why, one step back
4

Updated changelogMichel Weststratebefore adoption8f44348

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

Doc improvementsMichel Weststratebefore adoptiona3fcf04

lines 6–8why, one step back
6
7---8

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

lines 9–11why, one step back
9* NPM: `npm install immer`
10* Yarn: `yarn add immer`11* CDN: Exposed global is `immer`

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

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

Readme improvementsMichel Weststratebefore adoptiondcedda8

line 14why, one step back
14

Updated readme linksMichel Weststratebefore adoption553b6ce

lines 15–16why, one step back
15---
16

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

line 17why, one step back
17* 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 18why, one step back
18* 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 19why, one step back
19* [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate

Updated readme linksMichel Weststratebefore adoption553b6ce

line 20why, one step back
20

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

line 21why, one step back
21Immer (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 22why, one step back
22

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

line 23why, one step back
23The 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 24why, one step back
24

Merge pull request #56 from jkhedani/masterMichel Weststratebefore adoption076fbd6

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

Doc improvementsMichel Weststratebefore adoptiona3fcf04

line 26why, one step back
26

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

line 27why, one step back
27Using 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 28why, one step back
28

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

line 29why, one step back
29A 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 30–32why, one step back
30
31## API32

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 34why, one step back
34

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 36why, one step back
36

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

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

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

line 38why, one step back
38

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 39–41why, one step back
39## Example
4041```javascript

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

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

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

line 43why, one step back
43

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 44–49why, one step back
44const baseState = [
45 {46 todo: "Learn typescript",47 done: true48 },49 {

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 51–54why, one step back
51 done: false
52 }53]54

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

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

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

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

Doc improvementsMichel Weststratebefore adoptiona3fcf04

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 58–60why, one step back
58})
59```60

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

line 61why, one step back
61The 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 62–77why, one step back
62
63```javascript64// the new item is only added to the next state,65// base state is unmodified66expect(baseState.length).toBe(2)67expect(nextState.length).toBe(3)6869// same for the changed 'done' prop70expect(baseState[1].done).toBe(false)71expect(nextState[1].done).toBe(true)7273// unchanged data is structurally shared74expect(nextState[0]).toBe(baseState[0])75// changed data not (dûh)76expect(nextState[1]).not.toBe(baseState[1])77```

Doc improvementsMichel Weststratebefore adoptiona3fcf04

lines 78–80why, one step back
78
79## Benefits80

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

lines 81–86why, one step back
81* Immutability with normal JavaScript objects and arrays. No new APIs to learn!
82* Strongly typed, no string based paths selectors etc.83* Structural sharing out of the box84* Object freezing out of the box85* Deep updates are a breeze86* Boilerplate reduction. Less noise, more concise code.

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 88why, one step back
88

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

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

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

line 90why, one step back
90

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 91–92why, one step back
91## Reducer Example
92

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 94–95why, one step back
94
95```javascript

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

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

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

lines 99–110why, one step back
99 switch (action.type) {
100 case RECEIVE_PRODUCTS:101 return {102 ...state,103 ...action.products.reduce((obj, product) => {104 obj[product.id] = product105 return obj106 }, {})107 }108 default:109 return state110 }

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 111–113why, one step back
111}
112```113

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 115–116why, one step back
115
116```javascript

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 118why, one step back
118

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

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

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

lines 120–127why, one step back
120 produce(state, draft => {
121 switch (action.type) {122 case RECEIVE_PRODUCTS:123 action.products.forEach(product => {124 draft[product.id] = product125 })126 }127 })

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 128–129why, one step back
128```
129

transpile es5 codeMichel Weststratebefore adoptionf012154

line 130why, one step back
130Notice 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 131why, one step back
131

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

line 132why, one step back
132Creating 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 133why, one step back
133

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

line 134why, one step back
134_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 135why, one step back
135

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

lines 136–137why, one step back
136## React.setState example
137

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

line 138why, one step back
138Deep 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 139–144why, one step back
139
140```javascript141/**142 * Classic React.setState with a deep merge143 */144onBirthDayClick1 = () => {

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

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

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

line 146why, one step back
146 user: {

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

lines 147–148why, one step back
147 ...prevState.user,
148 age: prevState.user.age + 1

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

line 149why, one step back
149 }

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

line 150why, one step back
150 }))

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

lines 151–154why, one step back
151}
152153/**154 * ...But, since setState accepts functions,

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

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

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

line 156why, one step back
156 */

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

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

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

lines 158–162why, one step back
158 this.setState(
159 produce(draft => {160 draft.user.age += 1161 })162 )

Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a

lines 163–165why, one step back
163}
164```165

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

lines 166–167why, one step back
166## Currying
167

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

line 168why, one step back
168Passing 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 169–185why, one step back
169
170For example:171172```javascript173// mapper will be of signature (state, index) => state174const mapper = produce((draft, index) => {175 draft.index = index176})177178// example usage179console.dir([{}, {}, {}].map(mapper))180//[{index: 0}, {index: 1}, {index: 2}])181```182183This mechanism can also nicely be leveraged to further simplify our example reducer:184185```javascript

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

lines 186–187why, one step back
186import produce from 'immer'
187

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

lines 188–190why, one step back
188const byId = produce((draft, action) => {
189 switch (action.type) {190 case RECEIVE_PRODUCTS:

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

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

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

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

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

line 193why, one step back
193 })

Readme improvementsMichel Weststratebefore adoptiondcedda8

line 194why, one step back
194 return

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

lines 195–201why, one step back
195 })
196 }197})198```199200Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).201

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

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

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

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

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

line 206why, one step back
206

Readme improvementsMichel Weststratebefore adoptiondcedda8

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

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

lines 208–218why, one step back
208 (draft, action) => {
209 switch (action.type) {210 case RECEIVE_PRODUCTS:211 action.products.forEach(product => {212 draft[product.id] = product213 })214 return215 }216 },217 {218 1: {id: 1, name: "product-1"}

Readme improvementsMichel Weststratebefore adoptiondcedda8

lines 219–220why, one step back
219 }
220)

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

lines 221–222why, one step back
221```
222

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 223–226why, one step back
223## Patches
224225During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer.226This 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 227–232why, one step back
227
228Patches are useful in few scenarios:229 * To exchange incremental updates with other parties, for example over websockets230 * For debugging / traces, to see precisely how state is changed over time231 * As basis for undo/redo or as approach to replay changes on a slightly different state tree232

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 233–303why, one step back
233To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used
234to record the incremental updates and (inverse) apply them:235236```javascript237import produce, {applyPatches} from "immer"238239let state = {240 name: "Micheal",241 age: 32242}243244// Let's assume the user is in a wizard, and we don't know whether245// his changes should be end up in the base state ultimately or not...246let fork = state247// all the changes the user made in the wizard248let changes = []249// the inverse of all the changes made in the wizard250let inverseChanges = []251252fork = produce(253 fork,254 draft => {255 draft.age = 33256 },257 // The third argument to produce is a callback to which the patches will be fed258 (patches, inversePatches) => {259 changes.push(...patches)260 inverseChanges.push(...inversePatches)261 }262)263264// In the mean time, our original state is replaced, as, for example,265// some changes were received from the server266state = produce(state, draft => {267 draft.name = "Michel"268})269270// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!271state = applyPatches(state, changes)272273// state now contains the changes from both code paths!274expect(state).toEqual({275 name: "Michel", // changed by the server276 age: 33 // changed by the wizard277})278279// Finally, even after finishing the wizard, the user might change his mind and undo his changes...280state = applyPatches(state, inverseChanges)281expect(state).toEqual({282 name: "Michel", // Not reverted283 age: 32 // Reverted284})285```286287The 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.288This 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:289290```json291[292 { "op": "replace", "path": ["profile"], "value": { "name": "Veria", age: 5 }},293 { "op": "remove", "path": ["tags", 3] }294]295```296297```json298[299 { "op": "replace", "path": ["profile"], "value": { "name": "Noa", age: 6 }},300 { "op": "add", "path": ["tags", 3], "value": "kiddo"},301]302```303

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

lines 304–305why, one step back
304## Auto freezing
305

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

line 306why, one step back
306Immer 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 307why, one step back
307

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

lines 308–309why, one step back
308## Returning data from producers
309

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

line 310why, one step back
310It 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 311why, one step back
311

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

line 312why, one step back
312It 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 313–315why, one step back
313
314```javascript315const userReducer = produce((draft, action) => {

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

lines 316–345why, one step back
316 switch (action.type) {
317 case "renameUser":318 // OK: we modify the current state319 draft.users[action.payload.id].name = action.payload.name320 return draft // same as just 'return'321 case "loadUsers":322 // OK: we return an entirely new state323 return action.payload324 case "adduser-1":325 // NOT OK: This doesn't do change the draft nor return a new state!326 // It doesn't modify the draft (it just redeclares it)327 // In fact, this just doesn't do anything at all328 draft = {users: [...draft.users, action.payload]}329 return330 case "adduser-2":331 // NOT OK: modifying draft *and* returning a new state332 draft.userCount += 1333 return {users: [...draft.users, action.payload]}334 case "adduser-3":335 // OK: returning a new state. But, unnecessary complex and expensive336 return {337 userCount: draft.userCount + 1,338 users: [...draft.users, action.payload]339 }340 case "adduser-4":341 // OK: the immer way342 draft.userCount += 1343 draft.users.push(action.payload)344 return345 }

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

lines 346–348why, one step back
346})
347```348

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

lines 349–355why, one step back
349## Using `this`
350351The recipe will be always invoked with the `draft` as `this` context.352353This means that the following constructions are also valid:354355```javascript

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

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

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

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

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

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

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

lines 360–364why, one step back
360})
361console.log(next.counter) // 1362363// OR364const increment = produce(function() {

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

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

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

lines 366–373why, one step back
366})
367console.log(increment(base).counter) // 1368```369370## TypeScript or Flow371372The 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.373

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

lines 374–387why, one step back
374The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:
375376```ts377import produce from 'immer';378379interface State {380 readonly x: number;381}382383// `x` cannot be modified here384const state: State = {385 x: 0;386};387

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

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

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

lines 389–397why, one step back
389 // `x` can be modified here
390 draft.x++;391});392393// `newState.x` cannot be modified here394```395396This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!397

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

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

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

line 399why, one step back
399

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

line 400why, one step back
400By 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 401why, one step back
401

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

lines 402–417why, one step back
402## Importing immer
403404`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:405406```javascript407import produce from "immer"408import { produce } from "immer"409410const { produce } = require("immer")411const produce = require("immer").produce412const produce = require("immer").default413414import unleashTheMagic from "immer"415import { produce as unleashTheMagic } from "immer"416```417

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

line 418why, one step back
418## Pitfalls

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 419why, one step back
419

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

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

Removed superfluos Redux examples (fixes #57). Explained working with Dates betterMichel Weststratebefore adoptiona7b5df7

line 421why, one step back
4211. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.

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

lines 422–425why, one step back
4221. 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), the changes will be persisted. But, both in your new and old state! So, in such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.
4231. 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.4241. 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`4251. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.

Updated changelogMichel Weststratebefore adoption5e8464d

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

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

line 427why, one step back
427

Added section with cool stuffMichel Weststratebefore adoption69aedd8

lines 428–429why, one step back
428## Cool things built with immer
429

Updated who uses sectionMichel Weststratebefore adoption0152244

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

Readme improvementsMichel Weststratebefore adoptiondcedda8

line 431why, one step back
431* [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 432–433why, one step back
432* [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_
433* [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 434why, one step back
434* [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux developement quicker and easier_

Updated who uses sectionMichel Weststratebefore adoption0152244

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

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

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

Updated who uses sectionMichel Weststratebefore adoption0152244

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

Added section with cool stuffMichel Weststratebefore adoption69aedd8

line 438why, one step back
438

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

lines 439–440why, one step back
439## How does Immer work?
440

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

line 441why, one step back
441Read 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 442why, one step back
442

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 443–446why, one step back
443## Example patterns.
444445_For those who have to go back to thinking in object updates :-)_446

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

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

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

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

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 449–451why, one step back
449
450// object mutations451const todosObj = {

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

lines 452–454why, one step back
452 id1: {done: false, body: "Take out the trash"},
453 id2: {done: false, body: "Check Email"}454}

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 455–457why, one step back
455
456// add457const addedTodosObj = produce(todosObj, draft => {

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

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

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 460–462why, one step back
460
461// delete462const deletedTodosObj = produce(todosObj, draft => {

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

lines 463–464why, one step back
463 delete draft["id1"]
464})

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 465–467why, one step back
465
466// update467const updatedTodosObj = produce(todosObj, draft => {

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

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

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 470–472why, one step back
470
471// array mutations472const todosArray = [

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

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

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 476–478why, one step back
476
477// add478const addedTodosArray = produce(todosArray, draft => {

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

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

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 481–483why, one step back
481
482// delete483const deletedTodosArray = produce(todosArray, draft => {

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

lines 484–487why, one step back
484 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)
485 // or (slower):486 // return draft.filter(todo => todo.id !== "id1")487})

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 488–490why, one step back
488
489// update490const updatedTodosArray = produce(todosArray, draft => {

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

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

Added examples as suggested by #115Michel Weststratebefore adoption3f64997

lines 493–494why, one step back
493```
494

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

lines 495–496why, one step back
495## Performance
496

Update readmeMichel Weststratebefore adoption341cfeb

line 497why, one step back
497Here 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 498why, one step back
498

Update readmeMichel Weststratebefore adoption341cfeb

line 499why, one step back
499These 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 500why, one step back
500

Fixed performance imagesMichel Weststratebefore adoption89e0d24

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

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

line 502why, one step back
502

Update readmeMichel Weststratebefore adoption341cfeb

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

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

line 504why, one step back
504

Update readmeMichel Weststratebefore adoption341cfeb

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

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

line 506why, one step back
506* 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 507–508why, one step back
507* Generating patches doesn't significantly slow immer down
508* 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 509why, one step back
509

Added FAQ sectionMichel Weststratebefore adoptionb9b418e

lines 510–537why, one step back
510## FAQ
511512_(for those who skimmed the above instead of actually reading)_513514**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**515516A: Yes517518**Q: Does Immer support deep updates?**519520A: Yes521522**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**523524A: Yes525526**Q: Can I typecheck my data structures when using Immer?**527528A: Yes529530**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**531532A: Yes533534**Q: Is it fast?**535536A: Yes537

Added question about freezingMichel Weststratebefore adoption6ac7707

lines 538–541why, one step back
538**Q: Idea! Can Immer freeze the state for me?**
539540A: Yes541

Added performance measurements, fixes #6Michel Weststratebefore adoption553299f

lines 542–544why, one step back
542## Credits
543544Special 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 545–548why, one step back
545
546## Donations547548A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)