Skip to content
Myr

readme.md

This file

Path

readme.md

299 lines · 12.7 KiB · Markdown

Last changed by

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

History of this file

Take it

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

Readme cleanupMichel Weststratebefore adoptiona3b49ff

line 3why, one step back
3[![Build Status](https://travis-ci.org/mweststrate/immer.svg?branch=master)](https://travis-ci.org/mweststrate/immer)

Merge pull request #25 from Gregjarvez/travisMichel Weststratebefore adoption55ec6d0

line 4why, one step back
4[![Coverage Status](https://coveralls.io/repos/github/mweststrate/immer/badge.svg?branch=master)](https://coveralls.io/github/mweststrate/immer?branch=master)

Readme cleanupMichel Weststratebefore adoptiona3b49ff

lines 5–6why, one step back
5[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
6[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://mobx.js.org/donate.html)

Merge pull request #25 from Gregjarvez/travisMichel Weststratebefore adoption55ec6d0

line 7why, one step back
7

Updated changelogMichel Weststratebefore adoption8f44348

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

Doc improvementsMichel Weststratebefore adoptiona3fcf04

lines 9–11why, one step back
9
10---11

Readme cleanupMichel Weststratebefore adoptiona3b49ff

line 12why, one step back
12* NPM / Yarn: `npm install immer`

transpile es5 codeMichel Weststratebefore adoptionf012154

line 13why, one step back
13* CDN: https://unpkg.com/immer/dist/immer.umd.js or https://unpkg.com/immer/dist/es5.umd.js. Exposed global is `immer`.

Merge pull request #39 from fkhadra/issue-7-add-badges-and-cdnMichel Weststratebefore adoption227e953

line 14why, one step back
14

Updated readme linksMichel Weststratebefore adoption553b6ce

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

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

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

Updated readme linksMichel Weststratebefore adoption553b6ce

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

Fixed typo and yarn.lockMichel Weststratebefore adoption101aac2

line 20why, one step back
20Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.

Readme improvementsMichel Weststratebefore adoption58e9b57

line 21why, one step back
21It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 22why, one step back
22

Readme improvementsMichel Weststratebefore adoption58e9b57

line 23why, one step back
23The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.

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

line 24why, one step back
24Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state.

Readme improvementsMichel Weststratebefore adoption58e9b57

line 25why, one step back
25This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 26why, one step back
26

Merge pull request #56 from jkhedani/masterMichel Weststratebefore adoption076fbd6

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

Doc improvementsMichel Weststratebefore adoptiona3fcf04

line 28why, one step back
28

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

line 29why, one step back
29Using Immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).

Readme improvementsMichel Weststratebefore adoption58e9b57

line 30why, one step back
30

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

line 31why, one step back
31A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applied to plain, native JavaScript data structures (arrays and objects) without further needing any library.

Doc improvementsMichel Weststratebefore adoptiona3fcf04

lines 32–34why, one step back
32
33## API34

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 36why, one step back
36

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 38why, one step back
38

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

lines 39–40why, one step back
39There is also a curried overload that is explained [below](#currying)
40

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 41–43why, one step back
41## Example
4243```javascript

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

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

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

line 45why, one step back
45

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 46–51why, one step back
46const baseState = [
47 {48 todo: "Learn typescript",49 done: true50 },51 {

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 53–56why, one step back
53 done: false
54 }55]56

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

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

Doc improvementsMichel Weststratebefore adoptiona3fcf04

lines 58–59why, one step back
58 draftState.push({ todo: "Tweet about it" })
59 draftState[1].done = true

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 60–62why, one step back
60})
61```62

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 64–79why, one step back
64
65```javascript66// the new item is only added to the next state,67// base state is unmodified68expect(baseState.length).toBe(2)69expect(nextState.length).toBe(3)7071// same for the changed 'done' prop72expect(baseState[1].done).toBe(false)73expect(nextState[1].done).toBe(true)7475// unchanged data is structurally shared76expect(nextState[0]).toBe(baseState[0])77// changed data not (dûh)78expect(nextState[1]).not.toBe(baseState[1])79```

Doc improvementsMichel Weststratebefore adoptiona3fcf04

lines 80–82why, one step back
80
81## Benefits82

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 89why, one step back
89

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

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

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

line 91why, one step back
91

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 100why, one step back
100 switch (action.type) {

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

line 101why, one step back
101 case RECEIVE_PRODUCTS:

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 102–103why, one step back
102 return {
103 ...state,

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

lines 104–107why, one step back
104 ...action.products.reduce((obj, product) => {
105 obj[product.id] = product106 return obj107 }, {})

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 108–114why, one step back
108 }
109 default:110 return state111 }112}113```114

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 119why, one step back
119

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

lines 120–121why, one step back
120const byId = (state, action) =>
121 produce(state, draft => {

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 122why, one step back
122 switch (action.type) {

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

lines 123–125why, one step back
123 case RECEIVE_PRODUCTS:
124 action.products.forEach(product => {125 draft[product.id] = product

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 126–130why, one step back
126 })
127 }128 })129```130

transpile es5 codeMichel Weststratebefore adoptionf012154

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 132why, one step back
132

transpile es5 codeMichel Weststratebefore adoptionf012154

line 133why, one step back
133Creating Redux reducer is just a sample application of the Immer package.

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

line 134why, one step back
134Immer is not just designed to simplify Redux reducers.

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 135–137why, one step back
135It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).
136137_Note: it might be tempting after using producers a while, to just put `produce` in your root reducer, and then past the draft along to each reducer and work on that. Don't do that. It kills the point of Redux where each reducer is testable as pure reducer. Immer is best used when applying it to small individual pieces of logic._

Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b

line 138why, one step back
138

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

lines 139–160why, one step back
139## Currying
140141`produce` can be called with one or two arguments.142The one argument version is intended to be used as currying. This means that you get a pre-pound producer, that only needs a state to produce the value from.143The producer function get's passed in the draft, and any further arguments that were passed to the curried function.144145For example:146147```javascript148// mapper will be of signature (state, index) => state149const mapper = produce((draft, index) => {150 draft.index = index151})152153// example usage154console.dir([{}, {}, {}].map(mapper))155//[{index: 0}, {index: 1}, {index: 2}])156```157158This mechanism can also nicely be leveraged to further simplify our example reducer:159160```javascript

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

lines 161–162why, one step back
161import produce from 'immer'
162

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

lines 163–189why, one step back
163const byId = produce((draft, action) => {
164 switch (action.type) {165 case RECEIVE_PRODUCTS:166 action.products.forEach(product => {167 draft[product.id] = product168 })169 }170})171```172173Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).174One think to keep in mind; you cannot use this construction to initialize an uninitialized state. E.g. `draft = {}` doesn't do anything useful.175176177## Auto freezing178179 Immer automatically freezes any state trees that are modified using `produce`.180 This protects against accidental modifications of the state tree outside of a producer.181 This comes with a performance impact, so it is recommended to disable this option in production.182 It is by default enabled.183 Use `setAutoFreeze(true / false)` to turn this feature on or off.184185## Using Immer on older JavaScript environments186187By default `produce` tries to use proxies for optimal performance.188However, on older JavaScript engines `Proxy` is not available.189For example, Microsoft Internet Explorer or React Native on Android.

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

lines 190–191why, one step back
190In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.
191However, if you want to slim down your bundle, you could only include the Proxy based implementation by importing from `immer/proxy`.

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

line 192why, one step back
192

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

lines 193–198why, one step back
193An overview of the available builds:
194195Immer exposes its functionality in 3 different ways:196* `import produce from "immer"`, the default, ships with both the Proxy and ES5 compatible implementation, and picks at runtime the best matching one. This is the most convenient, but adds the most to the bundle size (~2KB)197* `import produce from "immer/proxy"`: This build is optimized for modern browser, which support Proxies and other modern language features, and doesn't polyfill things like `Symbol`. Use this if you are targetting a modern environment only198* `import produce from "immer/es5"`: Only bundle the ES5 compatible implementation (which of course also works for modern browsers)

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

lines 199–201why, one step back
199
200## More reducer examples201

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

line 202why, one step back
202Here are some typical reducer examples, take from the Redux [Immutable Update Patterns](https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) page, and their Immer counter part.

Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b

lines 203–216why, one step back
203These examples are semantically equivalent and produce the exact same state.
204205```javascript206// Plain reducer207function insertItem(array, action) {208 return [209 ...array.slice(0, action.index),210 action.item,211 ...array.slice(action.index)212 ]213}214215// With immer216function insertItem(array, action) {

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

line 217why, one step back
217 return produce(array, draft => {

Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b

lines 218–231why, one step back
218 draft.splice(action.index, 0, action.item)
219 })220}221222// Plain reducer223function removeItem(array, action) {224 return [225 ...array.slice(0, action.index),226 ...array.slice(action.index + 1)227 ];228}229230// With immer231function removeItem(array, action) {

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

line 232why, one step back
232 return produce(array, draft => {

Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b

lines 233–243why, one step back
233 draft.splice(action.index, 1)
234 })235}236237// Plain reducer238function updateObjectInArray(array, action) {239 return array.map( (item, index) => {240 if(index !== action.index) {241 // This isn't the item we care about - keep it as-is242 return item;243 }

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

line 244why, one step back
244

Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b

lines 245–254why, one step back
245 // Otherwise, this is the one we want - return an updated value
246 return {247 ...item,248 ...action.item249 };250 });251}252253// With immer254function updateObjectInArray(array, action) {

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

line 255why, one step back
255 return produce(array, draft => {

Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b

line 256why, one step back
256 draft[action.index] = { ...item, ...action.item}

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

line 257why, one step back
257 // Alternatively, since arbitrarily deep updates are supported:

Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b

lines 258–262why, one step back
258 // Object.assign(draft[action.index], action.item)
259 })260}261```262

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

line 263why, one step back
263## Pitfalls

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 264why, one step back
264

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

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

Readme improvementsMichel Weststratebefore adoptiona1f5c6a

line 266why, one step back
266* Immer only processes native arrays and plain objects (with a prototype of `null` or `Object`). Any other type of value will be treated verbatim! So if you modify a `Map` or `Buffer` or whatever complex object from the draft state, it will be that very same object in both the base state as the next state. In such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.

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

line 267why, one step back
267* 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`

Readme improvementsMichel Weststratebefore adoptiona1f5c6a

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

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

line 269why, one step back
269

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

lines 270–271why, one step back
270## How does Immer work?
271

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

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

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

line 273why, one step back
273

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

lines 274–275why, one step back
274## Performance
275

Merge pull request #55 from typicode/patch-1Michel Weststratebefore adoption804703b

line 276why, one step back
276Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer.

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

lines 277–282why, one step back
277This test takes 100.000 todo items, and updates 10.000 of them.
278_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.279280These tests were executed on Node 8.4.0.281Use `yarn test:perf` to reproduce them locally.282

Fixed performance imagesMichel Weststratebefore adoption89e0d24

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

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

lines 284–286why, one step back
284
285Some observations:286* The _mutate_, and _deepclone, mutate_ benchmarks establish a baseline on how expensive changing the data is, without immutability (or structural sharing in the deep clone case).

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

line 287why, one step back
287* The _reducer_ and _naive reducer_ are implemented in typical Redux style reducers. The "smart" implementation slices the collection first, and then maps and freezes only the relevant todos. The "naive" implementation just maps over and processes the entire collection.

Fixed #49Michel Weststratebefore adoption5227173

line 288why, one step back
288* Immer with proxies is roughly speaking twice as slow as a hand written reducer. This is in practice negligible.

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

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

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

line 290why, one step back
290* The ES5 implementation of Immer is significantly slower. For most reducers this won't matter, but reducers that process large amounts of data might benefit from not (or only partially) using an Immer producer. Luckily, Immer is fully opt-in.

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

line 291why, one step back
291* The peeks in the _frozen_ versions of _just mutate_, _deepclone_ and _naive reducer_ come from the fact that they recursively freeze the full state tree, while the other test cases only freeze the modified parts of the tree.

Added performance measurements, fixes #6Michel Weststratebefore adoption553299f

lines 292–295why, one step back
292
293## Credits294295Special thanks goes to @Mendix, which supports it's employees to experiment completely freely two full days a month, which formed the kick-start for this project.

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

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