readme.md
This file
Path
readme.md
451 lines · 18.0 KiB · Markdown
Last changed by
Update readme with note on new mapped Draft type.Kenneth Powersbefore adoptionb66a9de
History of this fileTake it
Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 1–2why, one step back1# Immer2Merge pull request #156 from styfle/patch-1Michel Weststratebefore adoptione0a8a1a
line 3why, one step back3[](https://www.npmjs.com/package/immer) [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js) [](https://packagephobia.now.sh/result?p=immer) [](https://travis-ci.org/mweststrate/immer) [](https://coveralls.io/github/mweststrate/immer?branch=master) [](https://github.com/prettier/prettier) [](https://www.paypal.me/michelweststrate)Merge pull request #25 from Gregjarvez/travisMichel Weststratebefore adoption55ec6d0
line 4why, one step back4Updated changelogMichel Weststratebefore adoption8f44348
line 5why, one step back5_Create the next immutable state tree by simply modifying the current tree_Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 6–8why, one step back67---8Merge pull request #123 from styfle/patch-1benbraoubefore adoption02fe6b1
lines 9–11why, one step back9* NPM: `npm install immer`10* Yarn: `yarn add immer`11* CDN: Exposed global is `immer`Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 12–13why, one step back12 * Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`13 * JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`Readme improvementsMichel Weststratebefore adoptiondcedda8
line 14why, one step back14Updated readme linksMichel Weststratebefore adoption553b6ce
lines 15–16why, one step back15---16Object.is for equality, more tests. Fixes #43, #42, #48Michel Weststratebefore adoptione29a792
line 17why, one step back17* 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 back18* Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)19Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 20why, one step back20Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way. It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 21why, one step back21Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 22why, one step back22The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_. Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state. This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 23why, one step back23Merge pull request #56 from jkhedani/masterMichel Weststratebefore adoption076fbd6
line 24why, one step back24Doc improvementsMichel Weststratebefore adoptiona3fcf04
line 25why, one step back25`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 26why, one step back26Using 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 27why, one step back27Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 28why, one step back28A 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 29–31why, one step back2930## API31Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 32why, one step back32The Immer package exposes a default function that does all the work.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 33why, one step back33`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 34why, one step back34`produce(currentState, producer: (draftState) => void): nextState`Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 35why, one step back35Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
line 36why, one step back36There is also a curried overload that is explained [below](#currying).Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 37why, one step back37Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 38–40why, one step back38## Example3940```javascript`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 41why, one step back41import produce from "immer"Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
line 42why, one step back42Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 43–48why, one step back43const baseState = [44 {45 todo: "Learn typescript",46 done: true47 },48 {Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 49why, one step back49 todo: "Try immer",Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 50–53why, one step back50 done: false51 }52]53`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 54why, one step back54const nextState = produce(baseState, draftState => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 55why, one step back55 draftState.push({todo: "Tweet about it"})Doc improvementsMichel Weststratebefore adoptiona3fcf04
line 56why, one step back56 draftState[1].done = trueFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 57–59why, one step back57})58```59Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 60why, one step back60The 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 61–76why, one step back6162```javascript63// the new item is only added to the next state,64// base state is unmodified65expect(baseState.length).toBe(2)66expect(nextState.length).toBe(3)6768// same for the changed 'done' prop69expect(baseState[1].done).toBe(false)70expect(nextState[1].done).toBe(true)7172// unchanged data is structurally shared73expect(nextState[0]).toBe(baseState[0])74// changed data not (dûh)75expect(nextState[1]).not.toBe(baseState[1])76```Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 77–79why, one step back7778## Benefits79Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 80–85why, one step back80* Immutability with normal JavaScript objects and arrays. No new APIs to learn!81* Strongly typed, no string based paths selectors etc.82* Structural sharing out of the box83* Object freezing out of the box84* Deep updates are a breeze85* Boilerplate reduction. Less noise, more concise code.Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0
line 86why, one step back86* Small: bundled and minified: 2KB.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 87why, one step back87Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 88why, one step back88Read further to see all these benefits explained.Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 89why, one step back89Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 90–91why, one step back90## Reducer Example91Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 92why, one step back92Here is a simple example of the difference that Immer could make in practice.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 93–94why, one step back9394```javascriptMerge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 95–97why, one step back95// Redux reducer96// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js97const byId = (state, action) => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 98–109why, one step back98 switch (action.type) {99 case RECEIVE_PRODUCTS:100 return {101 ...state,102 ...action.products.reduce((obj, product) => {103 obj[product.id] = product104 return obj105 }, {})106 }107 default:108 return state109 }Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 110–112why, one step back110}111```112Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 113why, one step back113After using Immer, that simply becomes:Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 114–115why, one step back114115```javascriptMerge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 116why, one step back116import produce from "immer"Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 117why, one step back117Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 118why, one step back118const byId = (state, action) =>Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 119–126why, one step back119 produce(state, draft => {120 switch (action.type) {121 case RECEIVE_PRODUCTS:122 action.products.forEach(product => {123 draft[product.id] = product124 })125 }126 })Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 127–128why, one step back127```128transpile es5 codeMichel Weststratebefore adoptionf012154
line 129why, one step back129Notice 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 130why, one step back130Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 131why, one step back131Creating Redux reducer is just a sample application of the Immer package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).transpile es5 codeMichel Weststratebefore adoptionf012154
line 132why, one step back132Merge pull request #114 from xaviergonz/patch-1Michel Weststratebefore adoptionc71b173
line 133why, one step back133_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 134why, one step back134Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
lines 135–136why, one step back135## React.setState example136Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 137why, one step back137Deep updates in the state of React components can be greatly simplified as well by using immer. Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
lines 138–143why, one step back138139```javascript140/**141 * Classic React.setState with a deep merge142 */143onBirthDayClick1 = () => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 144why, one step back144 this.setState(prevState => ({Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
line 145why, one step back145 user: {Merge pull request #104 from mikollo/patch-1Michel Weststratebefore adoptionc047a59
lines 146–147why, one step back146 ...prevState.user,147 age: prevState.user.age + 1Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
line 148why, one step back148 }Merge pull request #104 from mikollo/patch-1Michel Weststratebefore adoptionc047a59
line 149why, one step back149 }))Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
lines 150–153why, one step back150}151152/**153 * ...But, since setState accepts functions,Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
line 154why, one step back154 * we can just create a curried producer and further simplify!Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 155why, one step back155 */Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
line 156why, one step back156onBirthDayClick2 = () => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 157–161why, one step back157 this.setState(158 produce(draft => {159 draft.user.age += 1160 })161 )Added `React.setState` exampleMichel Weststratebefore adoption2c8a71a
lines 162–164why, one step back162}163```164Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 165–166why, one step back165## Currying166Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 167why, one step back167Passing a function as the first argument to `produce` is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from. The producer function gets passed in the draft, and any further arguments that were passed to the curried function.Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 168–184why, one step back168169For example:170171```javascript172// mapper will be of signature (state, index) => state173const mapper = produce((draft, index) => {174 draft.index = index175})176177// example usage178console.dir([{}, {}, {}].map(mapper))179//[{index: 0}, {index: 1}, {index: 2}])180```181182This mechanism can also nicely be leveraged to further simplify our example reducer:183184```javascriptFixed configurability of array.length on proxies. Fixes #50Michel Weststratebefore adoption1c7df26
lines 185–186why, one step back185import produce from 'immer'186Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 187–189why, one step back187const byId = produce((draft, action) => {188 switch (action.type) {189 case RECEIVE_PRODUCTS:Merge pull request #71 from Keysox/patch-1Michel Weststratebefore adoptiond47db4d
line 190why, one step back190 action.products.forEach(product => {Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 191why, one step back191 draft[product.id] = productMerge pull request #71 from Keysox/patch-1Michel Weststratebefore adoptiond47db4d
line 192why, one step back192 })Readme improvementsMichel Weststratebefore adoptiondcedda8
line 193why, one step back193 returnMerge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 194–200why, one step back194 })195 }196})197```198199Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).200Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
lines 201–203why, one step back201If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:202203```javascriptMerge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 204why, one step back204import produce from "immer"Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
line 205why, one step back205Readme improvementsMichel Weststratebefore adoptiondcedda8
line 206why, one step back206const byId = produce(Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 207–217why, one step back207 (draft, action) => {208 switch (action.type) {209 case RECEIVE_PRODUCTS:210 action.products.forEach(product => {211 draft[product.id] = product212 })213 return214 }215 },216 {217 1: {id: 1, name: "product-1"}Readme improvementsMichel Weststratebefore adoptiondcedda8
lines 218–219why, one step back218 }219)Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
lines 220–221why, one step back220```221Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 222–223why, one step back222## Auto freezing223Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 224why, one step back224Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default it is turned on during local development, and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 225why, one step back225Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
lines 226–227why, one step back226## Returning data from producers227Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 228why, one step back228It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway. However, it is allowed to just `return draft`.Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
line 229why, one step back229Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 230why, one step back230It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft. This can be useful to produce an entirely new state. Some examples:Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
lines 231–233why, one step back231232```javascript233const userReducer = produce((draft, action) => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 234–263why, one step back234 switch (action.type) {235 case "renameUser":236 // OK: we modify the current state237 draft.users[action.payload.id].name = action.payload.name238 return draft // same as just 'return'239 case "loadUsers":240 // OK: we return an entirely new state241 return action.payload242 case "adduser-1":243 // NOT OK: This doesn't do change the draft nor return a new state!244 // It doesn't modify the draft (it just redeclares it)245 // In fact, this just doesn't do anything at all246 draft = {users: [...draft.users, action.payload]}247 return248 case "adduser-2":249 // NOT OK: modifying draft *and* returning a new state250 draft.userCount += 1251 return {users: [...draft.users, action.payload]}252 case "adduser-3":253 // OK: returning a new state. But, unnecessary complex and expensive254 return {255 userCount: draft.userCount + 1,256 users: [...draft.users, action.payload]257 }258 case "adduser-4":259 // OK: the immer way260 draft.userCount += 1261 draft.users.push(action.payload)262 return263 }Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
lines 264–266why, one step back264})265```266Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
lines 267–273why, one step back267## Using `this`268269The recipe will be always invoked with the `draft` as `this` context.270271This means that the following constructions are also valid:272273```javascriptMerge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 274why, one step back274const base = {counter: 0}Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
lines 275–276why, one step back275276const next = produce(base, function() {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 277why, one step back277 this.counter++Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
lines 278–282why, one step back278})279console.log(next.counter) // 1280281// OR282const increment = produce(function() {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 283why, one step back283 this.counter++Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
lines 284–291why, one step back284})285console.log(increment(base).counter) // 1286```287288## TypeScript or Flow289290The 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.291Update readme with note on new mapped Draft type.Kenneth Powersbefore adoptionb66a9de
lines 292–315why, one step back292The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:293294```ts295import produce from 'immer';296297interface State {298 readonly x: number;299}300301// `x` cannot be modified here302const state: State = {303 x: 0;304};305306const newState = produce<State>(draft => {307 // `x` can be modified here308 draft.x++;309});310311// `newState.x` cannot be modified here312```313314This ensures that the only place you can modify your state is in your produce callbacks.315Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0
line 316why, one step back316## Immer on older JavaScript environments?Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 317why, one step back317Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 318why, one step back318By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In 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 319–320why, one step back319320## PitfallsFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 321why, one step back321Implemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
line 322why, one step back3221. 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
line 323why, one step back3231. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 324–327why, one step back3241. 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.3251. 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.3261. 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`3271. 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 328why, one step back328Added section with cool stuffMichel Weststratebefore adoption69aedd8
lines 329–330why, one step back329## Cool things built with immer330Updated who uses sectionMichel Weststratebefore adoption0152244
line 331why, one step back331* [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_Readme improvementsMichel Weststratebefore adoptiondcedda8
line 332why, one step back332* [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 333–334why, one step back333* [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_334* [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 335why, one step back335* [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux developement quicker and easier_Updated who uses sectionMichel Weststratebefore adoption0152244
lines 336–337why, one step back336* [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_337* ... and [many more](https://www.npmjs.com/browse/depended/immer)Added section with cool stuffMichel Weststratebefore adoption69aedd8
line 338why, one step back338Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 339–340why, one step back339## How does Immer work?340Object.is for equality, more tests. Fixes #43, #42, #48Michel Weststratebefore adoptione29a792
line 341why, one step back341Read 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 342why, one step back342Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 343–346why, one step back343## Example patterns.344345_For those who have to go back to thinking in object updates :-)_346Merge pull request #124 from capaj/patch-1benbraoubefore adoptionbbedb9f
line 347why, one step back347```javascriptMerge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 348why, one step back348import produce from "immer"Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 349–351why, one step back349350// object mutations351const todosObj = {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 352–354why, one step back352 id1: {done: false, body: "Take out the trash"},353 id2: {done: false, body: "Check Email"}354}Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 355–357why, one step back355356// add357const addedTodosObj = produce(todosObj, draft => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 358–359why, one step back358 draft["id3"] = {done: false, body: "Buy bananas"}359})Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 360–362why, one step back360361// delete362const deletedTodosObj = produce(todosObj, draft => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 363–364why, one step back363 delete draft["id1"]364})Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 365–367why, one step back365366// update367const updatedTodosObj = produce(todosObj, draft => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 368–369why, one step back368 draft["id1"].done = true369})Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 370–372why, one step back370371// array mutations372const todosArray = [Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 373–375why, one step back373 {id: "id1", done: false, body: "Take out the trash"},374 {id: "id2", done: false, body: "Check Email"}375]Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 376–378why, one step back376377// add378const addedTodosArray = produce(todosArray, draft => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 379–380why, one step back379 draft.push({id: "id3", done: false, body: "Buy bananas"})380})Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 381–383why, one step back381382// delete383const deletedTodosArray = produce(todosArray, draft => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 384–387why, one step back384 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)385 // or (slower):386 // return draft.filter(todo => todo.id !== "id1")387})Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 388–390why, one step back388389// update390const updatedTodosArray = produce(todosArray, draft => {Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
lines 391–392why, one step back391 draft[draft.findIndex(todo => todo.id === "id1")].done = true392})Added examples as suggested by #115Michel Weststratebefore adoption3f64997
lines 393–394why, one step back393```394Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 395–396why, one step back395## Performance396Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 397why, one step back397Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 100.000 todo items, and updates 10.000 of them. _Freeze_ indicates that the state tree has been frozen after producing it. This is a _development_ best practice, as it prevents developers from accidentally modifying the state tree.Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
line 398why, one step back398Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 399why, one step back399These tests were executed on Node 8.4.0. Use `yarn test:perf` to reproduce them locally.Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
line 400why, one step back400Fixed performance imagesMichel Weststratebefore adoption89e0d24
line 401why, one step back401Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 402–403why, one step back402403Some observations:Merge branch 'kachkaev-add-failing-tests-for-recursive-use'Michel Weststratebefore adoption3db727b
line 404why, one step back404Documented 1.0.0 release!Michel Weststratebefore adoption5e16b30
line 405why, one step back405* 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 406why, one step back406* 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 407why, one step back407* 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 408why, one step back408* 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 409why, one step back409* 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 410why, one step back410* 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 #154 from knpwrs/patch-1benbraoubefore adoption26f22e9
line 411why, one step back411* The peaks 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 412why, one step back412Added FAQ sectionMichel Weststratebefore adoptionb9b418e
lines 413–440why, one step back413## FAQ414415_(for those who skimmed the above instead of actually reading)_416417**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**418419A: Yes420421**Q: Does Immer support deep updates?**422423A: Yes424425**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**426427A: Yes428429**Q: Can I typecheck my data structures when using Immer?**430431A: Yes432433**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**434435A: Yes436437**Q: Is it fast?**438439A: Yes440Added question about freezingMichel Weststratebefore adoption6ac7707
lines 441–444why, one step back441**Q: Idea! Can Immer freeze the state for me?**442443A: Yes444Added performance measurements, fixes #6Michel Weststratebefore adoption553299f
lines 445–447why, one step back445## Credits446447Special 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 448–451why, one step back448449## Donations450451A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)