Skip to content
Myr

readme.md

This file

Path

readme.md

294 lines · 12.3 KiB · Markdown

Last changed by

Merge pull request #90 from yeojz/readme-patch-1Michel Weststratebefore adoption3e1dcea

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`

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

line 13why, one step back
13* CDN: https://unpkg.com/immer/dist/immer.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.

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 90why, one step back
90

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

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

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

line 92why, one step back
92

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

line 102why, one step back
102 case RECEIVE_PRODUCTS:

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

lines 105–108why, one step back
105 ...action.products.reduce((obj, product) => {
106 obj[product.id] = product107 return obj108 }, {})

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 109–115why, one step back
109 }
110 default:111 return state112 }113}114```115

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 120why, one step back
120

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

transpile es5 codeMichel Weststratebefore adoptionf012154

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

transpile es5 codeMichel Weststratebefore adoptionf012154

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

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

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

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 136–138why, one step back
136It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).
137138_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 139why, one step back
139

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

lines 140–142why, one step back
140## Currying
141142`produce` can be called with one or two arguments.

Merge pull request #90 from yeojz/readme-patch-1Michel Weststratebefore adoption3e1dcea

lines 143–144why, one step back
143The one argument version 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.
144The producer function gets passed in the draft, and any further arguments that were passed to the curried function.

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

lines 145–161why, one step back
145
146For example:147148```javascript149// mapper will be of signature (state, index) => state150const mapper = produce((draft, index) => {151 draft.index = index152})153154// example usage155console.dir([{}, {}, {}].map(mapper))156//[{index: 0}, {index: 1}, {index: 2}])157```158159This mechanism can also nicely be leveraged to further simplify our example reducer:160161```javascript

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

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

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

lines 164–166why, one step back
164const byId = produce((draft, action) => {
165 switch (action.type) {166 case RECEIVE_PRODUCTS:

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

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

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

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

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

line 169why, one step back
169 })

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

lines 170–183why, one step back
170 })
171 }172})173```174175Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).176One think to keep in mind; you cannot use this construction to initialize an uninitialized state. E.g. `draft = {}` doesn't do anything useful.177178## Auto freezing179180 Immer automatically freezes any state trees that are modified using `produce`.181 This protects against accidental modifications of the state tree outside of a producer.182 This comes with a performance impact, so it is recommended to disable this option in production.183 It is by default enabled.

Disable auto freeze in production, fixes #46, also see #76Michel Weststratebefore adoption71d5909

line 184why, one step back
184 By default it is turned on during local development, and turned off in production.

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

line 185why, one step back
185 Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.

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

line 186why, one step back
186

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

lines 187–211why, one step back
187## Using `this`
188189The recipe will be always invoked with the `draft` as `this` context.190191This means that the following constructions are also valid:192193```javascript194const base = { counter: 0 }195196const next = produce(base, function() {197 this.counter++198})199console.log(next.counter) // 1200201// OR202const increment = produce(function() {203 this.counter++204})205console.log(increment(base).counter) // 1206```207208## TypeScript or Flow209210The 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.211

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

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

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

lines 213–215why, one step back
213
214By default `produce` tries to use proxies for optimal performance.215However, on older JavaScript engines `Proxy` is not available.

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

line 216why, one step back
216For example, when running Microsoft Internet Explorer or React Native on Android.

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

line 217why, one step back
217In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.

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

lines 218–219why, one step back
218
219## Pitfalls

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 220why, one step back
220

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

lines 221–225why, one step back
2211. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.
2222. Immer only processes native arrays and plain objects (with a prototype of `null` or `Object`). Any other type of value will be treated verbatim! So if you modify a `Map` or `Buffer` (or whatever complex object from the draft state), the changes will be persisted. But, both in your new and old state! So, in such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.2233. For example, working with `Date` objects is no problem, just make sure you never modify them (by using methods like `setYear` on an existing instance). Instead, always create fresh `Date` instances. Which is probably what you were unconsciously doing already.2244. 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`2255. 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 226why, one step back
226

Added section with cool stuffMichel Weststratebefore adoption69aedd8

lines 227–231why, one step back
227## Cool things built with immer
228229* [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_230* [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_231

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

lines 232–233why, one step back
232## How does Immer work?
233

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

line 234why, one step back
234Read 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 235why, one step back
235

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

lines 236–237why, one step back
236## Performance
237

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

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

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

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

Fixed performance imagesMichel Weststratebefore adoption89e0d24

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

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

lines 246–247why, one step back
246
247Some observations:

Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30

line 248why, one step back
248* From `immer` perspective, this benchmark is a _worst case_ scenario, because the root collection it has to proxy is really large relatively to the rest of the data set.

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

line 249why, one step back
249* 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 250why, one step back
250* 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 251why, one step back
251* 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 252why, one step back
252* 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 253why, one step back
253* 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 254why, one step back
254* 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

line 255why, one step back
255

Added FAQ sectionMichel Weststratebefore adoptionb9b418e

lines 256–283why, one step back
256## FAQ
257258_(for those who skimmed the above instead of actually reading)_259260**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**261262A: Yes263264**Q: Does Immer support deep updates?**265266A: Yes267268**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**269270A: Yes271272**Q: Can I typecheck my data structures when using Immer?**273274A: Yes275276**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**277278A: Yes279280**Q: Is it fast?**281282A: Yes283

Added question about freezingMichel Weststratebefore adoption6ac7707

lines 284–287why, one step back
284**Q: Idea! Can Immer freeze the state for me?**
285286A: Yes287

Added performance measurements, fixes #6Michel Weststratebefore adoption553299f

lines 288–290why, one step back
288## Credits
289290Special 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 291–294why, one step back
291
292## Donations293294A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)