Skip to content
Myr

readme.md

This file

Path

readme.md

779 lines · 30.7 KiB · Markdown

Last changed by

Update readme.md (#334)Noitidartbefore adoptionab7a44b

History of this file

Take it

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

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

lines 1–8why, one step back
1<img src="images/immer-logo.png" height="200px" align="right"/>
23# Immer45[![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)67_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

chore: add "Release notes" link to readmealeclarsonbefore adoption1803dd8

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

More readme linksMichel Weststratebefore adoptiond4a165b

line 13why, 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>

added some readme clarificationsMichel Weststratebefore adoption897c284

line 14why, one step back
14

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

lines 15–16why, one step back
15---
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>`

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

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)

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

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.

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

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

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

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

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

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)

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

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.

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

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

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

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.

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

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

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

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

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

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

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

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,

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

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

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

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

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

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:

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

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]}

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

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"}

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

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

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

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:

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

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

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

lines 381–421why, 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```421

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

line 422why, one step back
422_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 423why, one step back
423

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

lines 424–425why, one step back
424## 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`:

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

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.

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

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"

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

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)

Less is moreMichel Weststratebefore adoption1802421

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

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

line 457why, one step back
457

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2

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

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

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"}]}

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

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

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

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.

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

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.

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

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:

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

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"

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

line 520why, one step back
520

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

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

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"

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

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

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

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

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.

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
551When 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 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:

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

line 554why, one step back
554

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

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

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

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

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

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") // ❌

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

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) // ✅

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

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

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

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

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

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

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

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–639why, 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}604605const newState = produce<State>(state, draft => {606 // `x` can be modified here607 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!614615**Note:** Immer v1.9+ supports Typescript v3.1+ only.616617## Using `this`618619_Deprecated, this will probably be removed in a next major version, see [#308](https://github.com/mweststrate/immer/issues/308)_620621The recipe will be always invoked with the `draft` as `this` context.622623This means that the following constructions are also valid:624625```javascript626const base = {counter: 0}627628const next = produce(base, function() {629 this.counter++630})631console.log(next.counter) // 1632633// OR634const increment = produce(function() {635 this.counter++636})637console.log(increment(base).counter) // 1638```639

docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b

lines 640–647why, one step back
640# Pitfalls
6416421. 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).6431. 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.6441. 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.6451. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.6461. 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)})`6471. 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.

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

lines 648–650why, one step back
648
649## Cool things built with immer650

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

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

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

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

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

lines 663–721why, one step back
663
664## How does Immer work?665666Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).667668## Example patterns.669670_For those who have to go back to thinking in object updates :-)_671672```javascript673import produce from "immer"674675// object mutations676const todosObj = {677 id1: {done: false, body: "Take out the trash"},678 id2: {done: false, body: "Check Email"}679}680681// add682const addedTodosObj = produce(todosObj, draft => {683 draft["id3"] = {done: false, body: "Buy bananas"}684})685686// delete687const deletedTodosObj = produce(todosObj, draft => {688 delete draft["id1"]689})690691// update692const updatedTodosObj = produce(todosObj, draft => {693 draft["id1"].done = true694})695696// array mutations697const todosArray = [698 {id: "id1", done: false, body: "Take out the trash"},699 {id: "id2", done: false, body: "Check Email"}700]701702// add703const addedTodosArray = produce(todosArray, draft => {704 draft.push({id: "id3", done: false, body: "Buy bananas"})705})706707// delete708const deletedTodosArray = produce(todosArray, draft => {709 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)710 // or (slower):711 // return draft.filter(todo => todo.id !== "id1")712})713714// update715const updatedTodosArray = produce(todosArray, draft => {716 draft[draft.findIndex(todo => todo.id === "id1")].done = true717})718```719720## Performance721

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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

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

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

chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa

lines 730–733why, one step back
730- 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.
731- 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)732- Generating patches doesn't significantly slow immer down733- 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 734–739why, one step back
734
735## Migration736737**Immer 1.\* -> 2.0**738739Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.

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

lines 740–774why, one step back
740
741## FAQ742743_(for those who skimmed the above instead of actually reading)_744745**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**746747A: Yes748749**Q: Does Immer support deep updates?**750751A: Yes752753**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**754755A: Yes756757**Q: Can I typecheck my data structures when using Immer?**758759A: Yes760761**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**762763A: Yes764765**Q: Is it fast?**766767A: Yes768769**Q: Idea! Can Immer freeze the state for me?**770771A: Yes772773## Credits774

Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c

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

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

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