readme.md
This file
Path
readme.md
446 lines · 16.8 KiB · Markdown
Last changed by
Readme improvementsMichel Weststratebefore adoptiondcedda8
History of this fileTake it
Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 1–2why, one step back1# Immer2Merge pull request #123 from styfle/patch-1benbraoubefore adoption02fe6b1
lines 3–4why, one step back3[](https://www.npmjs.com/package/immer)4[](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)Readme cleanupMichel Weststratebefore adoptiona3b49ff
line 5why, one step back5[](https://travis-ci.org/mweststrate/immer)Merge pull request #25 from Gregjarvez/travisMichel Weststratebefore adoption55ec6d0
line 6why, one step back6[](https://coveralls.io/github/mweststrate/immer?branch=master)Readme cleanupMichel Weststratebefore adoptiona3b49ff
line 7why, one step back7[](https://github.com/prettier/prettier)Simpler donate linkMichel Weststratebefore adoption782bf82
line 8why, one step back8[](https://www.paypal.me/michelweststrate)Merge pull request #25 from Gregjarvez/travisMichel Weststratebefore adoption55ec6d0
line 9why, one step back9Updated changelogMichel Weststratebefore adoption8f44348
line 10why, one step back10_Create the next immutable state tree by simply modifying the current tree_Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 11–13why, one step back1112---13Merge pull request #123 from styfle/patch-1benbraoubefore adoption02fe6b1
lines 14–18why, one step back14* NPM: `npm install immer`15* Yarn: `yarn add immer`16* CDN: Exposed global is `immer`17 * Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`18 * JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`Readme improvementsMichel Weststratebefore adoptiondcedda8
line 19why, one step back19Updated readme linksMichel Weststratebefore adoption553b6ce
lines 20–21why, one step back20---21Object.is for equality, more tests. Fixes #43, #42, #48Michel Weststratebefore adoptione29a792
line 22why, one step back22* 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 23–24why, one step back23* Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)24Fixed typo and yarn.lockMichel Weststratebefore adoption101aac2
line 25why, one step back25Immer (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 26why, one step back26It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 27why, one step back27Readme improvementsMichel Weststratebefore adoption58e9b57
line 28why, one step back28The 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 29why, one step back29Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state.Readme improvementsMichel Weststratebefore adoption58e9b57
line 30why, one step back30This 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 31why, one step back31Merge pull request #56 from jkhedani/masterMichel Weststratebefore adoption076fbd6
line 32why, one step back32Doc improvementsMichel Weststratebefore adoptiona3fcf04
line 33why, one step back33`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 34why, one step back34Using 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 35why, one step back35Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 36why, one step back36A 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 37–39why, one step back3738## API39Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 40why, one step back40The Immer package exposes a default function that does all the work.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 41why, one step back41`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 42why, one step back42`produce(currentState, producer: (draftState) => void): nextState`Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 43why, one step back43Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
line 44why, one step back44There is also a curried overload that is explained [below](#currying).Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 45why, one step back45Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 46–48why, one step back46## Example4748```javascript`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 49why, one step back49import produce from "immer"Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
line 50why, one step back50Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 51–56why, one step back51const baseState = [52 {53 todo: "Learn typescript",54 done: true55 },56 {Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 57why, one step back57 todo: "Try immer",Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 58–61why, one step back58 done: false59 }60]61`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 62why, one step back62const nextState = produce(baseState, draftState => {Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 63–64why, one step back63 draftState.push({ todo: "Tweet about it" })64 draftState[1].done = trueFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 65–67why, one step back65})66```67Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 68why, one step back68The 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 69–84why, one step back6970```javascript71// the new item is only added to the next state,72// base state is unmodified73expect(baseState.length).toBe(2)74expect(nextState.length).toBe(3)7576// same for the changed 'done' prop77expect(baseState[1].done).toBe(false)78expect(nextState[1].done).toBe(true)7980// unchanged data is structurally shared81expect(nextState[0]).toBe(baseState[0])82// changed data not (dûh)83expect(nextState[1]).not.toBe(baseState[1])84```Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 85–87why, one step back8586## Benefits87Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 88–93why, one step back88* Immutability with normal JavaScript objects and arrays. No new APIs to learn!89* Strongly typed, no string based paths selectors etc.90* Structural sharing out of the box91* Object freezing out of the box92* Deep updates are a breeze93* Boilerplate reduction. Less noise, more concise code.Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0
line 94why, one step back94* Small: bundled and minified: 2KB.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 95why, one step back95Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 96why, one step back96Read further to see all these benefits explained.Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 97why, one step back97Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 98–99why, one step back98## Reducer Example99Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 100why, one step back100Here is a simple example of the difference that Immer could make in practice.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 101–102why, one step back101102```javascriptMerge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 103–105why, one step back103// Redux reducer104// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js105const byId = (state, action) => {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 106why, one step back106 switch (action.type) {Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 107why, one step back107 case RECEIVE_PRODUCTS:Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 108–109why, one step back108 return {109 ...state,Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 110–113why, one step back110 ...action.products.reduce((obj, product) => {111 obj[product.id] = product112 return obj113 }, {})Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 114–120why, one step back114 }115 default:116 return state117 }118}119```120Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 121why, one step back121After using Immer, that simply becomes:Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 122–123why, one step back122123```javascript`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 124why, one step back124import produce from 'immer'Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 125why, one step back125Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 126–127why, one step back126const byId = (state, action) =>127 produce(state, draft => {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 128why, one step back128 switch (action.type) {Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 129–131why, one step back129 case RECEIVE_PRODUCTS:130 action.products.forEach(product => {131 draft[product.id] = productFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 132–136why, one step back132 })133 }134 })135```136transpile es5 codeMichel Weststratebefore adoptionf012154
line 137why, one step back137Notice 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 138why, one step back138transpile es5 codeMichel Weststratebefore adoptionf012154
line 139why, one step back139Creating Redux reducer is just a sample application of the Immer package.Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 140why, one step back140Immer is not just designed to simplify Redux reducers.transpile es5 codeMichel Weststratebefore adoptionf012154
lines 141–142why, one step back141It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).142Merge pull request #114 from xaviergonz/patch-1Michel Weststratebefore adoptionc71b173
line 143why, one step back143_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._Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b
line 144why, one step back144Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
lines 145–154why, one step back145## React.setState example146147Deep updates in the state of React components can be greatly simplified as well by using immer.148Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):149150```javascript151/**152 * Classic React.setState with a deep merge153 */154onBirthDayClick1 = () => {Merge pull request #104 from mikollo/patch-1Michel Weststratebefore adoptionc047a59
line 155why, one step back155 this.setState((prevState)=>({Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
line 156why, one step back156 user: {Merge pull request #104 from mikollo/patch-1Michel Weststratebefore adoptionc047a59
lines 157–158why, one step back157 ...prevState.user,158 age: prevState.user.age + 1Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
line 159why, one step back159 }Merge pull request #104 from mikollo/patch-1Michel Weststratebefore adoptionc047a59
line 160why, one step back160 }))Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
lines 161–164why, one step back161}162163/**164 * ...But, since setState accepts functions,Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
line 165why, one step back165 * we can just create a curried producer and further simplify!Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
lines 166–169why, one step back166*/167onBirthDayClick2 = () => {168 this.setState(produce(draft => {169 draft.user.age += 1Merge pull request #106 from asamiller/patch-1benbraoubefore adoption5281004
line 170why, one step back170 }))Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
lines 171–173why, one step back171}172```173Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 174–175why, one step back174## Currying175Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
line 176why, one step back176Passing 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.Merge pull request #90 from yeojz/readme-patch-1Michel Weststratebefore adoption3e1dcea
line 177why, one step back177The 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 178–194why, one step back178179For example:180181```javascript182// mapper will be of signature (state, index) => state183const mapper = produce((draft, index) => {184 draft.index = index185})186187// example usage188console.dir([{}, {}, {}].map(mapper))189//[{index: 0}, {index: 1}, {index: 2}])190```191192This mechanism can also nicely be leveraged to further simplify our example reducer:193194```javascriptFixed configurability of array.length on proxies. Fixes #50Michel Weststratebefore adoption1c7df26
lines 195–196why, one step back195import produce from 'immer'196Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 197–199why, one step back197const byId = produce((draft, action) => {198 switch (action.type) {199 case RECEIVE_PRODUCTS:Merge pull request #71 from Keysox/patch-1Michel Weststratebefore adoptiond47db4d
line 200why, one step back200 action.products.forEach(product => {Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 201why, one step back201 draft[product.id] = productMerge pull request #71 from Keysox/patch-1Michel Weststratebefore adoptiond47db4d
line 202why, one step back202 })Readme improvementsMichel Weststratebefore adoptiondcedda8
line 203why, one step back203 returnMerge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 204–210why, one step back204 })205 }206})207```208209Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).210Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
lines 211–215why, one step back211If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:212213```javascript214import produce from 'immer'215Readme improvementsMichel Weststratebefore adoptiondcedda8
lines 216–227why, one step back216const byId = produce(217 (draft, action) => {218 switch (action.type) {219 case RECEIVE_PRODUCTS:220 action.products.forEach(product => {221 draft[product.id] = product222 })223 return224 }225 },226 {227 1: { id: 1, name: "product-1" }Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
line 228why, one step back228 }Readme improvementsMichel Weststratebefore adoptiondcedda8
line 229why, one step back229)Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
lines 230–231why, one step back230```231Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 232–237why, one step back232## Auto freezing233234 Immer automatically freezes any state trees that are modified using `produce`.235 This protects against accidental modifications of the state tree outside of a producer.236 This comes with a performance impact, so it is recommended to disable this option in production.237 It is by default enabled.Disable auto freeze in production, fixes #46, also see #76Michel Weststratebefore adoption71d5909
line 238why, one step back238 By default it is turned on during local development, and turned off in production.Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
line 239why, one step back239 Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 240why, one step back240Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
lines 241–243why, one step back241## Returning data from producers242243It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway.Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
line 244why, one step back244However, it is allowed to just `return draft`.Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
line 245why, one step back245Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
line 246why, one step back246It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft.Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
lines 247–283why, one step back247This can be useful to produce an entirely new state. Some examples:248249```javascript250const userReducer = produce((draft, action) => {251 switch (action.type) {252 case "renameUser":253 // OK: we modify the current state254 draft.users[action.payload.id].name = action.payload.name255 return draft // same as just 'return'256 case "loadUsers":257 // OK: we return an entirely new state258 return action.payload259 case "adduser-1":260 // NOT OK: This doesn't do change the draft nor return a new state!261 // It doesn't modify the draft (it just redeclares it)262 // In fact, this just doesn't do anything at all263 draft = { users: [...draft.users, action.payload]}264 return265 case "adduser-2":266 // NOT OK: modifying draft *and* returning a new state267 draft.userCount += 1268 return { users: [...draft.users, action.payload] }269 case "adduser-3":270 // OK: returning a new state. But, unnecessary complex and expensive271 return {272 userCount: draft.userCount + 1,273 users: [...draft.users, action.payload]274 }275 case "adduser-4":276 // OK: the immer way277 draft.userCount += 1278 draft.push(action.payload)279 return280 }281})282```283Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
lines 284–308why, one step back284## Using `this`285286The recipe will be always invoked with the `draft` as `this` context.287288This means that the following constructions are also valid:289290```javascript291const base = { counter: 0 }292293const next = produce(base, function() {294 this.counter++295})296console.log(next.counter) // 1297298// OR299const increment = produce(function() {300 this.counter++301})302console.log(increment(base).counter) // 1303```304305## TypeScript or Flow306307The 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.308Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0
line 309why, one step back309## Immer on older JavaScript environments?Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 310–312why, one step back310311By default `produce` tries to use proxies for optimal performance.312However, on older JavaScript engines `Proxy` is not available.Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0
line 313why, one step back313For example, when running Microsoft Internet Explorer or React Native on Android.Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 314why, one step back314In 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 315–316why, one step back315316## PitfallsFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 317why, one step back317Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
line 318why, one step back3181. 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).Removed superfluos Redux examples (fixes #57). Explained working with Dates betterMichel Weststratebefore adoptiona7b5df7
lines 319–323why, one step back3191. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.3202. 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.3213. 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.3224. 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`3235. 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 324why, one step back324Added section with cool stuffMichel Weststratebefore adoption69aedd8
lines 325–326why, one step back325## Cool things built with immer326Readme improvementsMichel Weststratebefore adoptiondcedda8
line 327why, one step back327* [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_Added section with cool stuffMichel Weststratebefore adoption69aedd8
lines 328–329why, one step back328* [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_329* [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_Merge pull request #122 from jeffreyyoung/patch-1Michel Weststratebefore adoption1b381ff
line 330why, one step back330* [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux developement quicker and easier_Added section with cool stuffMichel Weststratebefore adoption69aedd8
line 331why, one step back331Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 332–333why, one step back332## How does Immer work?333Object.is for equality, more tests. Fixes #43, #42, #48Michel Weststratebefore adoptione29a792
line 334why, one step back334Read 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 335why, one step back335Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 336–387why, one step back336## Example patterns.337338_For those who have to go back to thinking in object updates :-)_339340```javscript341import produce from "immer";342343// object mutations344const todosObj = {345 id1: { done: false, body: "Take out the trash" },346 id2: { done: false, body: "Check Email" }347};348349// add350const addedTodosObj = produce(todosObj, draft => {351 draft["id3"] = { done: false, body: "Buy bananas" };352});353354// delete355const deletedTodosObj = produce(todosObj, draft => {356 delete draft["id1"];357});358359// update360const updatedTodosObj = produce(todosObj, draft => {361 draft["id1"].done = true;362});363364// array mutations365const todosArray = [366 { id: "id1", done: false, body: "Take out the trash" },367 { id: "id2", done: false, body: "Check Email" }368];369370// add371const addedTodosArray = produce(todosArray, draft => {372 draft.push({ id: "id3", done: false, body: "Buy bananas" });373});374375// delete376const deletedTodosArray = produce(todosArray, draft => {377 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1);378 // or (slower):379 // return draft.filter(todo => todo.id !== "id1")380});381382// update383const updatedTodosArray = produce(todosArray, draft => {384 draft[draft.findIndex(todo => todo.id === "id1")].done = true;385});386```387Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 388–389why, one step back388## Performance389Merge pull request #55 from typicode/patch-1Michel Weststratebefore adoption804703b
line 390why, one step back390Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer.Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 391–396why, one step back391This test takes 100.000 todo items, and updates 10.000 of them.392_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.393394These tests were executed on Node 8.4.0.395Use `yarn test:perf` to reproduce them locally.396Fixed performance imagesMichel Weststratebefore adoption89e0d24
line 397why, one step back397Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 398–399why, one step back398399Some observations:Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
line 400why, one step back400* 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 401why, one step back401* 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 402why, one step back402* 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 403why, one step back403* 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 404why, one step back404* 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 405why, one step back405* 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 406why, one step back406* 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 407why, one step back407Added FAQ sectionMichel Weststratebefore adoptionb9b418e
lines 408–435why, one step back408## FAQ409410_(for those who skimmed the above instead of actually reading)_411412**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**413414A: Yes415416**Q: Does Immer support deep updates?**417418A: Yes419420**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**421422A: Yes423424**Q: Can I typecheck my data structures when using Immer?**425426A: Yes427428**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**429430A: Yes431432**Q: Is it fast?**433434A: Yes435Added question about freezingMichel Weststratebefore adoption6ac7707
lines 436–439why, one step back436**Q: Idea! Can Immer freeze the state for me?**437438A: Yes439Added performance measurements, fixes #6Michel Weststratebefore adoption553299f
lines 440–442why, one step back440## Credits441442Special 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 443–446why, one step back443444## Donations445446A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)