Skip to content
Myr

readme.md

This file

Path

readme.md

788 lines · 30.8 KiB · Markdown

Last changed by

docs: Readme fixesMichel Weststratebefore adoption980474a

History of this file

Take it

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

docs: remove install size badgeMichel Weststratebefore adoption7820eee

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) [![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)

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653

lines 9–10why, one step back
9Winner of the "breakthrough of the year" [open source award](https://osawards.com/react/) in 2019
10

feat: Immer now has it's own Github org, `immerjs`Michel Weststratebefore adoption17d69c3

line 11why, one step back
11### [Release notes](https://github.com/immerjs/immer/releases)

chore: add "Release notes" link to readmealeclarsonbefore adoption1803dd8

line 12why, one step back
12

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 13–16why, one step back
13Did 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>
1415---16

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 22–24why, one step back
22
23---24

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 27–29why, one step back
27
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.29

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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.

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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).

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

Added some external resources to readmeMichel Weststratebefore adoptionc018c49

lines 38–39why, one step back
38## External resources
39

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 40–44why, one step back
40- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)
41- 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)42- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)43- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)44- [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 45why, one step back
45- [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 46why, one step back
46

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 47–96why, one step back
47## API
4849The Immer package exposes a default function that does all the work.5051`produce(currentState, producer: (draftState) => void): nextState`5253There is also a curried overload that is explained [below](#currying).5455## Example5657```javascript58import produce from "immer"5960const baseState = [61 {62 todo: "Learn typescript",63 done: true64 },65 {66 todo: "Try immer",67 done: false68 }69]7071const nextState = produce(baseState, draftState => {72 draftState.push({todo: "Tweet about it"})73 draftState[1].done = true74})75```7677The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.7879```javascript80// the new item is only added to the next state,81// base state is unmodified82expect(baseState.length).toBe(2)83expect(nextState.length).toBe(3)8485// same for the changed 'done' prop86expect(baseState[1].done).toBe(false)87expect(nextState[1].done).toBe(true)8889// unchanged data is structurally shared90expect(nextState[0]).toBe(baseState[0])91// changed data not (dûh)92expect(nextState[1]).not.toBe(baseState[1])93```9495## Benefits96

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

line 103why, one step back
103- 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)

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 104–183why, one step back
104
105Read further to see all these benefits explained.106107## Reducer Example108109Here is a simple example of the difference that Immer could make in practice.110111```javascript112// Redux reducer113// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js114const byId = (state, action) => {115 switch (action.type) {116 case RECEIVE_PRODUCTS:117 return {118 ...state,119 ...action.products.reduce((obj, product) => {120 obj[product.id] = product121 return obj122 }, {})123 }124 default:125 return state126 }127}128```129130After using Immer, that simply becomes:131132```javascript133import produce from "immer"134135const byId = (state, action) =>136 produce(state, draft => {137 switch (action.type) {138 case RECEIVE_PRODUCTS:139 action.products.forEach(product => {140 draft[product.id] = product141 })142 }143 })144```145146Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.147148Creating 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).149150_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._151152## React.setState example153154Deep 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)):155156```javascript157/**158 * Classic React.setState with a deep merge159 */160onBirthDayClick1 = () => {161 this.setState(prevState => ({162 user: {163 ...prevState.user,164 age: prevState.user.age + 1165 }166 }))167}168169/**170 * ...But, since setState accepts functions,171 * we can just create a curried producer and further simplify!172 */173onBirthDayClick2 = () => {174 this.setState(175 produce(draft => {176 draft.user.age += 1177 })178 )179}180```181182## Currying183

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 185–236why, one step back
185
186For example:187188```javascript189// mapper will be of signature (state, index) => state190const mapper = produce((draft, index) => {191 draft.index = index192})193194// example usage195console.dir([{}, {}, {}].map(mapper))196//[{index: 0}, {index: 1}, {index: 2}])197```198199This mechanism can also nicely be leveraged to further simplify our example reducer:200201```javascript202import produce from 'immer'203204const byId = produce((draft, action) => {205 switch (action.type) {206 case RECEIVE_PRODUCTS:207 action.products.forEach(product => {208 draft[product.id] = product209 })210 return211 })212 }213})214```215216Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).217218If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:219220```javascript221import produce from "immer"222223const byId = produce(224 (draft, action) => {225 switch (action.type) {226 case RECEIVE_PRODUCTS:227 action.products.forEach(product => {228 draft[product.id] = product229 })230 return231 }232 },233 {234 1: {id: 1, name: "product-1"}235 }236)

Added some external resources to readmeMichel Weststratebefore adoptionc018c49

lines 237–240why, one step back
237```
238239##### Fun with currying240

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 241why, one step back
241A 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 242–248why, one step back
242
243```javascript244import produce from "immer"245const spread = produce(Object.assign)246247const base = {x: 1, y: 1}248

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

Added some external resources to readmeMichel Weststratebefore adoptionc018c49

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 252–255why, one step back
252```
253254## Patches255

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 256why, one step back
256During 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.

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 257–259why, one step back
257
258Patches are useful in few scenarios:259

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 263why, one step back
263

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 264–265why, one step back
264To 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:
265

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 266–274why, one step back
266```javascript
267import produce, {applyPatches} from "immer"268269let state = {270 name: "Micheal",271 age: 32272}273274// Let's assume the user is in a wizard, and we don't know whether

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 276–293why, one step back
276let fork = state
277// all the changes the user made in the wizard278let changes = []279// the inverse of all the changes made in the wizard280let inverseChanges = []281282fork = produce(283 fork,284 draft => {285 draft.age = 33286 },287 // The third argument to produce is a callback to which the patches will be fed288 (patches, inversePatches) => {289 changes.push(...patches)290 inverseChanges.push(...inversePatches)291 }292)293

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 295–305why, one step back
295// some changes were received from the server
296state = produce(state, draft => {297 draft.name = "Michel"298})299300// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!301state = applyPatches(state, changes)302303// state now contains the changes from both code paths!304expect(state).toEqual({305 name: "Michel", // changed by the server

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 314–316why, one step back
314})
315```316

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 318–320why, one step back
318
319```json320[

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 327–331why, one step back
327]
328```329330```json331[

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 334–336why, one step back
334]
335```336

Added link to immer patch articleMichel Weststratebefore adoption255d135

lines 337–338why, one step back
337For 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)
338

Added note about compressing patchesMichel Weststratebefore adoption7cae55b

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 342why, one step back
342

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 343why, one step back
343It 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:

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 344why, one step back
344

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 345–353why, one step back
345```javascript
346import produce from "immer"347348const user = {349 name: "michel",350 todos: []351}352353const loadedUser = await produce(user, async function(draft) {

docs: fixed error in docsMichel Weststratebefore adoption42b14bd

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 355–380why, one step back
355})
356```357358_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._359360## `createDraft` and `finishDraft`361362`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:363364```javascript365import {createDraft, finishDraft} from "immer"366367const user = {368 name: "michel",369 todos: []370}371372const draft = createDraft(user)373draft.todos = await (await window.fetch("http://host/" + draft.name)).json()374const loadedUser = finishDraft(draft)375```376377Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.378379_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._380

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 381–425why, one step back
381## Returning data from producers
382383It 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`.384385It 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:386387```javascript388const userReducer = produce((draft, action) => {389 switch (action.type) {390 case "renameUser":391 // OK: we modify the current state392 draft.users[action.payload.id].name = action.payload.name393 return draft // same as just 'return'394 case "loadUsers":395 // OK: we return an entirely new state396 return action.payload397 case "adduser-1":398 // NOT OK: This doesn't do change the draft nor return a new state!399 // It doesn't modify the draft (it just redeclares it)400 // In fact, this just doesn't do anything at all401 draft = {users: [...draft.users, action.payload]}402 return403 case "adduser-2":404 // NOT OK: modifying draft *and* returning a new state405 draft.userCount += 1406 return {users: [...draft.users, action.payload]}407 case "adduser-3":408 // OK: returning a new state. But, unnecessary complex and expensive409 return {410 userCount: draft.userCount + 1,411 users: [...draft.users, action.payload]412 }413 case "adduser-4":414 // OK: the immer way415 draft.userCount += 1416 draft.users.push(action.payload)417 return418 }419})420```421422_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._423424## Producing `undefined` using `nothing`425

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 427–442why, one step back
427
428```javascript429produce({}, draft => {430 // don't do anything431})432```433434Versus:435436```javascript437produce({}, draft => {438 // Try to return undefined from the producer439 return undefined440})441```442

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 456–457why, one step back
456// Both return the original state: { hello: "world"}
457

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 464–479why, one step back
464## Inline shortcuts using `void`
465466Draft 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.467468In 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`.469470```javascript471// Single mutation472produce(draft => void (draft.user.age += 1))473474// Multiple mutations475produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))476```477478Code 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.479

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 486–490why, one step back
486const nextState = produce(baseState, draftState => {
487 original(draftState.users) // is === baseState.users488})489```490

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

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

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

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

line 495why, one step back
495

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

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

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

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

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

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 506why, one step back
506

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 508–510why, one step back
508
509## Immer on older JavaScript environments?510

Update readme.md (#334)Noitidartbefore adoptionab7a44b

line 511why, one step back
511By 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 (< v0.59) on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 512–514why, one step back
512
513## Importing immer514

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 516–518why, one step back
516
517```javascript518import produce from "immer"

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 520why, one step back
520

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 522–525why, one step back
522const produce = require("immer").produce
523const produce = require("immer").default524525import unleashTheMagic from "immer"

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 527–528why, one step back
527```
528

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 530why, one step back
530

docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56

lines 531–535why, one step back
531Plain objects and arrays are always drafted by Immer.
532533Every 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.534535```js

[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653

line 536why, one step back
536import {immerable} from "immer"

docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56

lines 537–538why, one step back
537
538class Foo {

[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653

line 539why, one step back
539 [immerable] = true // Option 1

docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56

line 540why, one step back
540

[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653

lines 541–543why, one step back
541 constructor() {
542 this[immerable] = true // Option 2543 }

docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56

lines 544–547why, one step back
544}
545546Foo[immerable] = true // Option 3547```

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

line 548why, one step back
548

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 550why, one step back
550

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 552why, one step back
552

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 554why, one step back
554

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 557–558why, one step back
557 set: new Set(),
558 map: new Map()

v1.7.2Michel Weststratebefore adoptioncbdd98c

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

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 563why, one step back
563

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 566why, one step back
566

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 569why, one step back
569

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

line 572why, one step back
572

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 573–583why, one step back
573 // Similarly, don't use any Map methods.
574 draft.map.set("foo", "bar") // ❌575576 // 1. Instead, clone the map (just once)577 const newMap = new Map(draft.map) // ✅578579 // 2. Mutate it580 newMap.set("foo", "bar")581582 // 3. Update the draft583 draft.map = newMap

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 584–585why, one step back
584})
585```

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

line 586why, one step back
586

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 587–604why, one step back
587## TypeScript or Flow
588589The 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.590591The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:592593```ts594import produce from "immer"595596interface State {597 readonly x: number598}599600// `x` cannot be modified here601const state: State = {602 x: 0603}604

docs: Update readmeMichel Weststratebefore adoptionfe2473f

line 605why, one step back
605const newState = produce(state, draft => {

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 606–614why, one step back
606 // `x` can be modified here
607 draft.x++608})609610// `newState.x` cannot be modified here611```612613This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!614

docs: Update readmeMichel Weststratebefore adoptionfe2473f

line 615why, one step back
615For curried reducers, the type is inferred from the first argument of recipe function, so make sure to type it. The `Draft` utility type can be used if the state argument type is immutable:

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 616why, one step back
616

docs: Update readmeMichel Weststratebefore adoptionfe2473f

lines 617–637why, one step back
617```ts
618import produce, {Draft} from "immer"619620interface State {621 readonly x: number622}623624// `x` cannot be modified here625const state: State = {626 x: 0627}628629const increment = produce((draft: Draft<State>, inc: number) => {630 // `x` can be modified here631 draft.x += inc632})633634const newState = increment(state, 2)635// `newState.x` cannot be modified here636```637

docs: Readme fixesMichel Weststratebefore adoption980474a

line 638why, one step back
638**Note:** Immer v1.9+ supports TypeScript v3.1+ only.

docs: Update readmeMichel Weststratebefore adoptionfe2473f

line 639why, one step back
639

docs: Readme fixesMichel Weststratebefore adoption980474a

line 640why, one step back
640**Note:** Immer v3.0+ supports TypeScript v3.4+ only.

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 641why, one step back
641

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 642–648why, one step back
642# Pitfalls
6436441. 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).6451. 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.6461. 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.6471. 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)})`6481. 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.

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 649–651why, one step back
649
650## Cool things built with immer651

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

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

line 660why, one step back
660- [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 661why, one step back
661- [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 662why, one step back
662- [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 663why, one step back
663- ... and [many more](https://www.npmjs.com/browse/depended/immer)

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 664–722why, one step back
664
665## How does Immer work?666667Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).668669## Example patterns.670671_For those who have to go back to thinking in object updates :-)_672673```javascript674import produce from "immer"675676// object mutations677const todosObj = {678 id1: {done: false, body: "Take out the trash"},679 id2: {done: false, body: "Check Email"}680}681682// add683const addedTodosObj = produce(todosObj, draft => {684 draft["id3"] = {done: false, body: "Buy bananas"}685})686687// delete688const deletedTodosObj = produce(todosObj, draft => {689 delete draft["id1"]690})691692// update693const updatedTodosObj = produce(todosObj, draft => {694 draft["id1"].done = true695})696697// array mutations698const todosArray = [699 {id: "id1", done: false, body: "Take out the trash"},700 {id: "id2", done: false, body: "Check Email"}701]702703// add704const addedTodosArray = produce(todosArray, draft => {705 draft.push({id: "id3", done: false, body: "Buy bananas"})706})707708// delete709const deletedTodosArray = produce(todosArray, draft => {710 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)711 // or (slower):712 // return draft.filter(todo => todo.id !== "id1")713})714715// update716const updatedTodosArray = produce(todosArray, draft => {717 draft[draft.findIndex(todo => todo.id === "id1")].done = true718})719```720721## Performance722

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 724–730why, one step back
724
725These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.726727![performance.png](images/performance.png)728729Most important observation:730

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 731–734why, one step back
731- 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.
732- 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)733- Generating patches doesn't significantly slow immer down734- 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 735–737why, one step back
735
736## Migration737

docs: stub migration guideMichel Weststratebefore adoption3149a4d

lines 738–741why, one step back
738**Immer 2.\* -> 3.0**
739740TODO741

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

docs: Update readmeMichel Weststratebefore adoptionfe2473f

lines 745–748why, one step back
745
746**Immer 2.1 -> 2.2**747748When using TypeScript, for curried reducers that are typed in the form `produce<Type>((arg) => { })`, rewrite this to `produce((arg: Type) => { })` or `produce((arg: Draft<Type>) => { })` for correct inference.

v1.7.2Michel Weststratebefore adoptioncbdd98c

lines 749–783why, one step back
749
750## FAQ751752_(for those who skimmed the above instead of actually reading)_753754**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**755756A: Yes757758**Q: Does Immer support deep updates?**759760A: Yes761762**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**763764A: Yes765766**Q: Can I typecheck my data structures when using Immer?**767768A: Yes769770**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**771772A: Yes773774**Q: Is it fast?**775776A: Yes777778**Q: Idea! Can Immer freeze the state for me?**779780A: Yes781782## Credits783

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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

v1.7.2Michel Weststratebefore adoptioncbdd98c

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