readme.md
This file
Path
readme.md
439 lines · 16.6 KiB · Markdown
Last changed by
Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption8e42349
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 adoption483706d
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 adoption483706d
lines 14–19why, 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>`19 Updated 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 adoption8e42349
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 adoption8e42349
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 })Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 203–209why, one step back203 })204 }205})206```207208Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).209Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption8e42349
lines 210–225why, one step back210If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:211212```javascript213import produce from 'immer'214215const byId = produce((draft, action) => {216 switch (action.type) {217 case RECEIVE_PRODUCTS:218 action.products.forEach(product => {219 draft[product.id] = product220 })221 })222 }223}, { 1: { id: 1, name: "product-1" } })224```225Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 226–231why, one step back226## Auto freezing227228 Immer automatically freezes any state trees that are modified using `produce`.229 This protects against accidental modifications of the state tree outside of a producer.230 This comes with a performance impact, so it is recommended to disable this option in production.231 It is by default enabled.Disable auto freeze in production, fixes #46, also see #76Michel Weststratebefore adoption71d5909
line 232why, one step back232 By default it is turned on during local development, and turned off in production.Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
line 233why, one step back233 Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 234why, one step back234Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
lines 235–237why, one step back235## Returning data from producers236237It 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 adoption8e42349
line 238why, one step back238However, it is allowed to just `return draft`.Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
line 239why, one step back239Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption8e42349
line 240why, one step back240It 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 241–277why, one step back241This can be useful to produce an entirely new state. Some examples:242243```javascript244const userReducer = produce((draft, action) => {245 switch (action.type) {246 case "renameUser":247 // OK: we modify the current state248 draft.users[action.payload.id].name = action.payload.name249 return draft // same as just 'return'250 case "loadUsers":251 // OK: we return an entirely new state252 return action.payload253 case "adduser-1":254 // NOT OK: This doesn't do change the draft nor return a new state!255 // It doesn't modify the draft (it just redeclares it)256 // In fact, this just doesn't do anything at all257 draft = { users: [...draft.users, action.payload]}258 return259 case "adduser-2":260 // NOT OK: modifying draft *and* returning a new state261 draft.userCount += 1262 return { users: [...draft.users, action.payload] }263 case "adduser-3":264 // OK: returning a new state. But, unnecessary complex and expensive265 return {266 userCount: draft.userCount + 1,267 users: [...draft.users, action.payload]268 }269 case "adduser-4":270 // OK: the immer way271 draft.userCount += 1272 draft.push(action.payload)273 return274 }275})276```277Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
lines 278–302why, one step back278## Using `this`279280The recipe will be always invoked with the `draft` as `this` context.281282This means that the following constructions are also valid:283284```javascript285const base = { counter: 0 }286287const next = produce(base, function() {288 this.counter++289})290console.log(next.counter) // 1291292// OR293const increment = produce(function() {294 this.counter++295})296console.log(increment(base).counter) // 1297```298299## TypeScript or Flow300301The 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.302Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0
line 303why, one step back303## Immer on older JavaScript environments?Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 304–306why, one step back304305By default `produce` tries to use proxies for optimal performance.306However, on older JavaScript engines `Proxy` is not available.Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0
line 307why, one step back307For example, when running Microsoft Internet Explorer or React Native on Android.Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 308why, one step back308In 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 309–310why, one step back309310## PitfallsFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 311why, one step back311Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
line 312why, one step back3121. 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 313–317why, one step back3131. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.3142. 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.3153. 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.3164. 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`3175. 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 318why, one step back318Added section with cool stuffMichel Weststratebefore adoption69aedd8
lines 319–322why, one step back319## Cool things built with immer320321* [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_322* [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 adoptionb56f538
line 323why, one step back323* [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux developement quicker and easier_Added section with cool stuffMichel Weststratebefore adoption69aedd8
line 324why, one step back324Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 325–326why, one step back325## How does Immer work?326Object.is for equality, more tests. Fixes #43, #42, #48Michel Weststratebefore adoptione29a792
line 327why, one step back327Read 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 328why, one step back328Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 329–380why, one step back329## Example patterns.330331_For those who have to go back to thinking in object updates :-)_332333```javscript334import produce from "immer";335336// object mutations337const todosObj = {338 id1: { done: false, body: "Take out the trash" },339 id2: { done: false, body: "Check Email" }340};341342// add343const addedTodosObj = produce(todosObj, draft => {344 draft["id3"] = { done: false, body: "Buy bananas" };345});346347// delete348const deletedTodosObj = produce(todosObj, draft => {349 delete draft["id1"];350});351352// update353const updatedTodosObj = produce(todosObj, draft => {354 draft["id1"].done = true;355});356357// array mutations358const todosArray = [359 { id: "id1", done: false, body: "Take out the trash" },360 { id: "id2", done: false, body: "Check Email" }361];362363// add364const addedTodosArray = produce(todosArray, draft => {365 draft.push({ id: "id3", done: false, body: "Buy bananas" });366});367368// delete369const deletedTodosArray = produce(todosArray, draft => {370 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1);371 // or (slower):372 // return draft.filter(todo => todo.id !== "id1")373});374375// update376const updatedTodosArray = produce(todosArray, draft => {377 draft[draft.findIndex(todo => todo.id === "id1")].done = true;378});379```380Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 381–382why, one step back381## Performance382Merge pull request #55 from typicode/patch-1Michel Weststratebefore adoption804703b
line 383why, one step back383Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer.Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 384–389why, one step back384This test takes 100.000 todo items, and updates 10.000 of them.385_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.386387These tests were executed on Node 8.4.0.388Use `yarn test:perf` to reproduce them locally.389Fixed performance imagesMichel Weststratebefore adoption89e0d24
line 390why, one step back390Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 391–392why, one step back391392Some observations:Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
line 393why, one step back393* 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 394why, one step back394* 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 395why, one step back395* 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 396why, one step back396* 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 397why, one step back397* 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 398why, one step back398* 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 399why, one step back399* 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 400why, one step back400Added FAQ sectionMichel Weststratebefore adoptionb9b418e
lines 401–428why, one step back401## FAQ402403_(for those who skimmed the above instead of actually reading)_404405**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**406407A: Yes408409**Q: Does Immer support deep updates?**410411A: Yes412413**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**414415A: Yes416417**Q: Can I typecheck my data structures when using Immer?**418419A: Yes420421**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**422423A: Yes424425**Q: Is it fast?**426427A: Yes428Added question about freezingMichel Weststratebefore adoption6ac7707
lines 429–432why, one step back429**Q: Idea! Can Immer freeze the state for me?**430431A: Yes432Added performance measurements, fixes #6Michel Weststratebefore adoption553299f
lines 433–435why, one step back433## Credits434435Special 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 436–439why, one step back436437## Donations438439A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)