Skip to content
Myr

readme.md

This file

Path

readme.md

777 lines · 30.6 KiB · Markdown

Last changed by

docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56

History of this file

Take it

The walk stopped after 200 commits: lines older than 84229e2 point at it.

Picked a logoMichel Weststratebefore adoptionf1ca2f6

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

updated changelogMichel Weststratebefore adoption84229e2

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 adoption84229e2

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

chore: add "Release notes" link to readmealeclarsonbefore adoption1803dd8

lines 9–10why, one step back
9### [Release notes](https://github.com/mweststrate/immer/releases)
10

More readme linksMichel Weststratebefore adoptiond4a165b

line 11why, one step back
11Did 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 12why, one step back
12

updated changelogMichel Weststratebefore adoption84229e2

lines 13–14why, one step back
13---
14

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 15–19why, one step back
15- NPM: `npm install immer`
16- Yarn: `yarn add immer`17- CDN: Exposed global is `immer`18 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`19 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`

updated changelogMichel Weststratebefore adoption84229e2

lines 20–22why, one step back
20
21---22

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 23–24why, one step back
23- 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)
24- Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)

updated changelogMichel Weststratebefore adoption84229e2

lines 25–27why, one step back
25
26Immer (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.27

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

line 28why, one step back
28The 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.

updated changelogMichel Weststratebefore adoption84229e2

lines 29–31why, one step back
29
30![immer-hd.png](images/hd/immer.png)31

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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

updated changelogMichel Weststratebefore adoption84229e2

lines 33–35why, one step back
33
34A 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.35

Added some external resources to readmeMichel Weststratebefore adoptionc018c49

lines 36–37why, one step back
36## External resources
37

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 38–42why, one step back
38- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)
39- 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)40- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)41- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)42- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate

docs: added ForwardJS talk by swyxMichel Weststratebefore adoption984434e

line 43why, one step back
43- [ForwardJS 2019: Immutability is Changing - From Immutable.js to Immer](https://www.youtube.com/watch?v=bFuRvcAEiHg&feature=youtu.be) by [shawn swyx wang](https://twitter.com/swyx/)

Added some external resources to readmeMichel Weststratebefore adoptionc018c49

line 44why, one step back
44

updated changelogMichel Weststratebefore adoption84229e2

lines 45–94why, one step back
45## API
4647The Immer package exposes a default function that does all the work.4849`produce(currentState, producer: (draftState) => void): nextState`5051There is also a curried overload that is explained [below](#currying).5253## Example5455```javascript56import produce from "immer"5758const baseState = [59 {60 todo: "Learn typescript",61 done: true62 },63 {64 todo: "Try immer",65 done: false66 }67]6869const nextState = produce(baseState, draftState => {70 draftState.push({todo: "Tweet about it"})71 draftState[1].done = true72})73```7475The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.7677```javascript78// the new item is only added to the next state,79// base state is unmodified80expect(baseState.length).toBe(2)81expect(nextState.length).toBe(3)8283// same for the changed 'done' prop84expect(baseState[1].done).toBe(false)85expect(nextState[1].done).toBe(true)8687// unchanged data is structurally shared88expect(nextState[0]).toBe(baseState[0])89// changed data not (dûh)90expect(nextState[1]).not.toBe(baseState[1])91```9293## Benefits94

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 95–100why, one step back
95- Immutability with normal JavaScript objects and arrays. No new APIs to learn!
96- Strongly typed, no string based paths selectors etc.97- Structural sharing out of the box98- Object freezing out of the box99- Deep updates are a breeze100- Boilerplate reduction. Less noise, more concise code.

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

updated changelogMichel Weststratebefore adoption84229e2

lines 102–181why, one step back
102
103Read further to see all these benefits explained.104105## Reducer Example106107Here is a simple example of the difference that Immer could make in practice.108109```javascript110// Redux reducer111// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js112const byId = (state, action) => {113 switch (action.type) {114 case RECEIVE_PRODUCTS:115 return {116 ...state,117 ...action.products.reduce((obj, product) => {118 obj[product.id] = product119 return obj120 }, {})121 }122 default:123 return state124 }125}126```127128After using Immer, that simply becomes:129130```javascript131import produce from "immer"132133const byId = (state, action) =>134 produce(state, draft => {135 switch (action.type) {136 case RECEIVE_PRODUCTS:137 action.products.forEach(product => {138 draft[product.id] = product139 })140 }141 })142```143144Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.145146Creating 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).147148_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._149150## React.setState example151152Deep 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)):153154```javascript155/**156 * Classic React.setState with a deep merge157 */158onBirthDayClick1 = () => {159 this.setState(prevState => ({160 user: {161 ...prevState.user,162 age: prevState.user.age + 1163 }164 }))165}166167/**168 * ...But, since setState accepts functions,169 * we can just create a curried producer and further simplify!170 */171onBirthDayClick2 = () => {172 this.setState(173 produce(draft => {174 draft.user.age += 1175 })176 )177}178```179180## Currying181

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

line 182why, one step back
182Passing 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.

updated changelogMichel Weststratebefore adoption84229e2

lines 183–234why, one step back
183
184For example:185186```javascript187// mapper will be of signature (state, index) => state188const mapper = produce((draft, index) => {189 draft.index = index190})191192// example usage193console.dir([{}, {}, {}].map(mapper))194//[{index: 0}, {index: 1}, {index: 2}])195```196197This mechanism can also nicely be leveraged to further simplify our example reducer:198199```javascript200import produce from 'immer'201202const byId = produce((draft, action) => {203 switch (action.type) {204 case RECEIVE_PRODUCTS:205 action.products.forEach(product => {206 draft[product.id] = product207 })208 return209 })210 }211})212```213214Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).215216If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:217218```javascript219import produce from "immer"220221const byId = produce(222 (draft, action) => {223 switch (action.type) {224 case RECEIVE_PRODUCTS:225 action.products.forEach(product => {226 draft[product.id] = product227 })228 return229 }230 },231 {232 1: {id: 1, name: "product-1"}233 }234)

Added some external resources to readmeMichel Weststratebefore adoptionc018c49

lines 235–238why, one step back
235```
236237##### Fun with currying238

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 239why, one step back
239A random fun example just for inspiration: a neat trick is to turn `Object.assign` into a producer to create a "spread" function that is smarter than the normal spread operator, as it doesn't produce a new state if the result doesn't actually change ([details & explanation](https://twitter.com/mweststrate/status/1045059430256119809)). Quick example:

Added some external resources to readmeMichel Weststratebefore adoptionc018c49

lines 240–246why, one step back
240
241```javascript242import produce from "immer"243const spread = produce(Object.assign)244245const base = {x: 1, y: 1}246

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 247why, one step back
247console.log({...base, y: 1} === base) // false

Added some external resources to readmeMichel Weststratebefore adoptionc018c49

lines 248–249why, one step back
248console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced
249console.log(spread(base, {y: 2}) === base) // false, produced a new object as it should

updated changelogMichel Weststratebefore adoption84229e2

lines 250–251why, one step back
250```
251

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 252–253why, one step back
252## Patches
253

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 254why, one step back
254During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer. This 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 255–257why, one step back
255
256Patches are useful in few scenarios:257

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 258–260why, one step back
258- To exchange incremental updates with other parties, for example over websockets
259- For debugging / traces, to see precisely how state is changed over time260- As basis for undo/redo or as an approach to replay changes on a slightly different state tree

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

line 261why, one step back
261

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 262–263why, one step back
262To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used to record the incremental updates and (inverse) apply them:
263

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 264–272why, one step back
264```javascript
265import produce, {applyPatches} from "immer"266267let state = {268 name: "Micheal",269 age: 32270}271272// Let's assume the user is in a wizard, and we don't know whether

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

line 273why, one step back
273// his changes should end up in the base state ultimately or not...

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 274–291why, one step back
274let fork = state
275// all the changes the user made in the wizard276let changes = []277// the inverse of all the changes made in the wizard278let inverseChanges = []279280fork = produce(281 fork,282 draft => {283 draft.age = 33284 },285 // The third argument to produce is a callback to which the patches will be fed286 (patches, inversePatches) => {287 changes.push(...patches)288 inverseChanges.push(...inversePatches)289 }290)291

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

line 292why, one step back
292// In the meantime, our original state is replaced, as, for example,

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 293–303why, one step back
293// some changes were received from the server
294state = produce(state, draft => {295 draft.name = "Michel"296})297298// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!299state = applyPatches(state, changes)300301// state now contains the changes from both code paths!302expect(state).toEqual({303 name: "Michel", // changed by the server

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 304why, one step back
304 age: 33 // changed by the wizard

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 305–310why, one step back
305})
306307// Finally, even after finishing the wizard, the user might change his mind and undo his changes...308state = applyPatches(state, inverseChanges)309expect(state).toEqual({310 name: "Michel", // Not reverted

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 311why, one step back
311 age: 32 // Reverted

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 312–314why, one step back
312})
313```314

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 315why, one step back
315The 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. This 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:

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 316–318why, one step back
316
317```json318[

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 319–324why, one step back
319 {
320 "op": "replace",321 "path": ["profile"],322 "value": {"name": "Veria", "age": 5}323 },324 {"op": "remove", "path": ["tags", 3]}

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 325–329why, one step back
325]
326```327328```json329[

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 330–331why, one step back
330 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},
331 {"op": "add", "path": ["tags", 3], "value": "kiddo"}

Merge branch 'patches'Michel Weststratebefore adoption2513fb8

lines 332–334why, one step back
332]
333```334

Added link to immer patch articleMichel Weststratebefore adoption255d135

lines 335–336why, one step back
335For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)
336

Added note about compressing patchesMichel Weststratebefore adoption7cae55b

lines 337–338why, one step back
337Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.
338

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 339why, one step back
339## Async producers

updated changelogMichel Weststratebefore adoption84229e2

line 340why, one step back
340

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 341why, one step back
341It is allowed to return Promise objects from recipes. Or, in other words, to use `async / await`. This can be pretty useful for long running processes, that only produce the new object once the promise chain resolves. Note that `produce` itself (even in the curried form) will return a promise if the producer is async. Example:

updated changelogMichel Weststratebefore adoption84229e2

line 342why, one step back
342

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 343–351why, one step back
343```javascript
344import produce from "immer"345346const user = {347 name: "michel",348 todos: []349}350351const loadedUser = await produce(user, async function(draft) {

docs: fixed error in docsMichel Weststratebefore adoption42b14bd

line 352why, one step back
352 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 353–378why, one step back
353})
354```355356_Warning: please note that the draft shouldn't be 'leaked' from the async process and stored else where. The draft will still be revoked as soon as the async process completes._357358## `createDraft` and `finishDraft`359360`createDraft` and `finishDraft` are two low-level functions that are mostly useful for libraries that build abstractions on top of immer. It avoids the need to always create a function in order to work with drafts. Instead, one can create a draft, modify it, and at some time in the future finish the draft, in which case the next immutable state will be produced. We could for example rewrite our above example as:361362```javascript363import {createDraft, finishDraft} from "immer"364365const user = {366 name: "michel",367 todos: []368}369370const draft = createDraft(user)371draft.todos = await (await window.fetch("http://host/" + draft.name)).json()372const loadedUser = finishDraft(draft)373```374375Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.376377_Warning: in general, we recommend to use `produce` instead of the `createDraft` / `finishDraft` combo, `produce` is less error prone in usage, and more clearly separates the concepts of mutability and immutability in your code base._378

updated changelogMichel Weststratebefore adoption84229e2

lines 379–419why, one step back
379## Returning data from producers
380381It 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`.382383It 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:384385```javascript386const userReducer = produce((draft, action) => {387 switch (action.type) {388 case "renameUser":389 // OK: we modify the current state390 draft.users[action.payload.id].name = action.payload.name391 return draft // same as just 'return'392 case "loadUsers":393 // OK: we return an entirely new state394 return action.payload395 case "adduser-1":396 // NOT OK: This doesn't do change the draft nor return a new state!397 // It doesn't modify the draft (it just redeclares it)398 // In fact, this just doesn't do anything at all399 draft = {users: [...draft.users, action.payload]}400 return401 case "adduser-2":402 // NOT OK: modifying draft *and* returning a new state403 draft.userCount += 1404 return {users: [...draft.users, action.payload]}405 case "adduser-3":406 // OK: returning a new state. But, unnecessary complex and expensive407 return {408 userCount: draft.userCount + 1,409 users: [...draft.users, action.payload]410 }411 case "adduser-4":412 // OK: the immer way413 draft.userCount += 1414 draft.users.push(action.payload)415 return416 }417})418```419

Merge pull request #197 from 0xflotus/patch-1Michel Weststratebefore adoption21ad96b

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

added some readme clarificationsMichel Weststratebefore adoption897c284

line 421why, one step back
421

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

lines 422–423why, one step back
422## Producing `undefined` using `nothing`
423

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 424why, one step back
424So, in general, one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft. There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

lines 425–440why, one step back
425
426```javascript427produce({}, draft => {428 // don't do anything429})430```431432Versus:433434```javascript435produce({}, draft => {436 // Try to return undefined from the producer437 return undefined438})439```440

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 441why, one step back
441The problem is that in JavaScript a function that doesn't return anything also returns `undefined`! So immer cannot differentiate between those different cases. So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

lines 442–445why, one step back
442
443However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:444445```javascript

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 446why, one step back
446import produce, {nothing} from "immer"

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

lines 447–451why, one step back
447
448const state = {449 hello: "world"450}451

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 452–453why, one step back
452produce(state, draft => {})
453produce(state, draft => undefined)

Less is moreMichel Weststratebefore adoption1802421

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

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

line 455why, one step back
455

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 456why, one step back
456produce(state, draft => nothing)

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

lines 457–461why, one step back
457// Produces a new state, 'undefined'
458```459460N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.461

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 462–477why, one step back
462## Inline shortcuts using `void`
463464Draft 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.465466In 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`.467468```javascript469// Single mutation470produce(draft => void (draft.user.age += 1))471472// Multiple mutations473produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))474```475476Code 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.477

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

lines 478–482why, one step back
478## Extracting the original object from a proxied instance
479480Immer 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.481482```js

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 483why, one step back
483const baseState = {users: [{name: "Richie"}]}

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

lines 484–488why, one step back
484const nextState = produce(baseState, draftState => {
485 original(draftState.users) // is === baseState.users486})487```488

Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417

lines 489–491why, one step back
489Just want to know if a value is a proxied instance? Use the `isDraft` function!
490491```js

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 492why, one step back
492import {isDraft} from "immer"

Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417

line 493why, one step back
493

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 494why, one step back
494const baseState = {users: [{name: "Bobby"}]}

Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417

line 495why, one step back
495const nextState = produce(baseState, draft => {

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 496–497why, one step back
496 isDraft(draft) // => true
497 isDraft(draft.users) // => true

Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417

lines 498–502why, one step back
498 isDraft(draft.users[0]) // => true
499})500isDraft(nextState) // => false501```502

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 503why, one step back
503## Auto freezing

updated changelogMichel Weststratebefore adoption84229e2

line 504why, one step back
504

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 505why, one step back
505Immer 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.

updated changelogMichel Weststratebefore adoption84229e2

lines 506–508why, one step back
506
507## Immer on older JavaScript environments?508

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

line 509why, one step back
509By 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.

updated changelogMichel Weststratebefore adoption84229e2

line 510why, one step back
510

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

lines 511–512why, one step back
511## Importing immer
512

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

line 513why, one step back
513`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 recommended:

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

lines 514–516why, one step back
514
515```javascript516import produce from "immer"

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 517why, one step back
517import {produce} from "immer"

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

line 518why, one step back
518

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 519why, one step back
519const {produce} = require("immer")

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

lines 520–523why, one step back
520const produce = require("immer").produce
521const produce = require("immer").default522523import unleashTheMagic from "immer"

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 524why, one step back
524import {produce as unleashTheMagic} from "immer"

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

lines 525–526why, one step back
525```
526

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

line 527why, one step back
527## Supported object types

updated changelogMichel Weststratebefore adoption84229e2

line 528why, one step back
528

docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56

lines 529–545why, one step back
529Plain objects and arrays are always drafted by Immer.
530531Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.532533```js534import {immerable} from 'immer'535536class Foo {537 [immerable] = true // Option 1538539 constructor() {540 this[immerable] = true // Option 2541 }542}543544Foo[immerable] = true // Option 3545```

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 546why, one step back
546

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

line 547why, one step back
547For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.

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

line 548why, one step back
548

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

line 549why, one step back
549When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.

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

line 550why, one step back
550

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

line 551why, one step back
551Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:

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

line 552why, one step back
552

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

line 553why, one step back
553```js

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

line 554why, one step back
554const state = {

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 555–556why, one step back
555 set: new Set(),
556 map: new Map()

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

lines 557–558why, one step back
557}
558const nextState = produce(state, draft => {

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 559–560why, one step back
559 // Don't use any Set methods, as that mutates the instance!
560 draft.set.add("foo") // ❌

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

line 561why, one step back
561

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 562–563why, one step back
562 // 1. Instead, clone the set (just once)
563 const newSet = new Set(draft.set) // ✅

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

line 564why, one step back
564

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 565–566why, one step back
565 // 2. Mutate the clone (just in this producer)
566 newSet.add("foo")

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

line 567why, one step back
567

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 568–569why, one step back
568 // 3. Update the draft with the new set
569 draft.set = newSet

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

line 570why, one step back
570

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 571–581why, one step back
571 // Similarly, don't use any Map methods.
572 draft.map.set("foo", "bar") // ❌573574 // 1. Instead, clone the map (just once)575 const newMap = new Map(draft.map) // ✅576577 // 2. Mutate it578 newMap.set("foo", "bar")579580 // 3. Update the draft581 draft.map = newMap

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

lines 582–583why, one step back
582})
583```

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

line 584why, one step back
584

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 585–637why, one step back
585## TypeScript or Flow
586587The 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.588589The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:590591```ts592import produce from "immer"593594interface State {595 readonly x: number596}597598// `x` cannot be modified here599const state: State = {600 x: 0601}602603const newState = produce<State>(state, draft => {604 // `x` can be modified here605 draft.x++606})607608// `newState.x` cannot be modified here609```610611This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!612613**Note:** Immer v1.9+ supports Typescript v3.1+ only.614615## Using `this`616617_Deprecated, this will probably be removed in a next major version, see [#308](https://github.com/mweststrate/immer/issues/308)_618619The recipe will be always invoked with the `draft` as `this` context.620621This means that the following constructions are also valid:622623```javascript624const base = {counter: 0}625626const next = produce(base, function() {627 this.counter++628})629console.log(next.counter) // 1630631// OR632const increment = produce(function() {633 this.counter++634})635console.log(increment(base).counter) // 1636```637

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 638–645why, one step back
638# Pitfalls
6396401. 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).6411. 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.6421. 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.6431. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.6441. 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)})`6451. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable 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

line 646why, one step back
646

updated changelogMichel Weststratebefore adoption84229e2

lines 647–648why, one step back
647## Cool things built with immer
648

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 649–656why, one step back
649- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_
650- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_651- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_652- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_653- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_654- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_655- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_656- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_

Merge pull request #285 from epeli/patch-1Michel Weststratebefore adoptionaf55671

line 657why, one step back
657- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse Redux reducers with Typescript_

docs: add redux-ts-utils to "cool things made with immer"Kenneth Powersbefore adoption0b6960a

line 658why, one step back
658- [redux-ts-utils](https://github.com/knpwrs/redux-ts-utils) _Everything you need to create type-safe applications with Redux with a strong emphasis on simplicity_

docs: add react-state-treeAlec Larsonbefore adoptiondfcd543

line 659why, one step back
659- [react-state-tree](https://github.com/suchipi/react-state-tree) _Drop-in replacement for useState that persists your state into a redux-like state tree_

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

updated changelogMichel Weststratebefore adoption84229e2

lines 661–719why, one step back
661
662## How does Immer work?663664Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).665666## Example patterns.667668_For those who have to go back to thinking in object updates :-)_669670```javascript671import produce from "immer"672673// object mutations674const todosObj = {675 id1: {done: false, body: "Take out the trash"},676 id2: {done: false, body: "Check Email"}677}678679// add680const addedTodosObj = produce(todosObj, draft => {681 draft["id3"] = {done: false, body: "Buy bananas"}682})683684// delete685const deletedTodosObj = produce(todosObj, draft => {686 delete draft["id1"]687})688689// update690const updatedTodosObj = produce(todosObj, draft => {691 draft["id1"].done = true692})693694// array mutations695const todosArray = [696 {id: "id1", done: false, body: "Take out the trash"},697 {id: "id2", done: false, body: "Check Email"}698]699700// add701const addedTodosArray = produce(todosArray, draft => {702 draft.push({id: "id3", done: false, body: "Buy bananas"})703})704705// delete706const deletedTodosArray = produce(todosArray, draft => {707 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)708 // or (slower):709 // return draft.filter(todo => todo.id !== "id1")710})711712// update713const updatedTodosArray = produce(todosArray, draft => {714 draft[draft.findIndex(todo => todo.id === "id1")].done = true715})716```717718## Performance719

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

line 720why, one step back
720Here 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.

updated changelogMichel Weststratebefore adoption84229e2

line 721why, one step back
721

Update readmeMichel Weststratebefore adoption341cfeb

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

updated changelogMichel Weststratebefore adoption84229e2

lines 723–725why, one step back
723
724![performance.png](images/performance.png)725

Update readmeMichel Weststratebefore adoption341cfeb

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

updated changelogMichel Weststratebefore adoption84229e2

line 727why, one step back
727

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 728–731why, one step back
728- Immer with proxies is roughly speaking twice to three times slower as a handwritten reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.
729- 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)730- Generating patches doesn't significantly slow immer down731- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 732–737why, one step back
732
733## Migration734735**Immer 1.\* -> 2.0**736737Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.

updated changelogMichel Weststratebefore adoption84229e2

lines 738–772why, one step back
738
739## FAQ740741_(for those who skimmed the above instead of actually reading)_742743**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**744745A: Yes746747**Q: Does Immer support deep updates?**748749A: Yes750751**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**752753A: Yes754755**Q: Can I typecheck my data structures when using Immer?**756757A: Yes758759**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**760761A: Yes762763**Q: Is it fast?**764765A: Yes766767**Q: Idea! Can Immer freeze the state for me?**768769A: Yes770771## Credits772

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

line 773why, one step back
773Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.

updated changelogMichel Weststratebefore adoption84229e2

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