readme.md
This file
Path
readme.md
290 lines · 11.6 KiB · Markdown
Last changed by
transpile es5 codeMichel Weststratebefore adoptionf012154
History of this fileTake it
Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 1–2why, one step back1# Immer2Readme cleanupMichel Weststratebefore adoptiona3b49ff
line 3why, one step back3[](https://travis-ci.org/mweststrate/immer)Merge pull request #25 from Gregjarvez/travisMichel Weststratebefore adoption55ec6d0
line 4why, one step back4[](https://coveralls.io/github/mweststrate/immer?branch=master)Readme cleanupMichel Weststratebefore adoptiona3b49ff
lines 5–6why, one step back5[](https://github.com/prettier/prettier)6[](https://mobx.js.org/donate.html)Merge pull request #25 from Gregjarvez/travisMichel Weststratebefore adoption55ec6d0
line 7why, one step back7Updated changelogMichel Weststratebefore adoption8f44348
line 8why, one step back8_Create the next immutable state tree by simply modifying the current tree_Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 9–11why, one step back910---11Readme cleanupMichel Weststratebefore adoptiona3b49ff
line 12why, one step back12* NPM / Yarn: `npm install immer`transpile es5 codeMichel Weststratebefore adoptionf012154
line 13why, one step back13* CDN: https://unpkg.com/immer/dist/immer.umd.js or https://unpkg.com/immer/dist/es5.umd.js. Exposed global is `immer`.Merge pull request #39 from fkhadra/issue-7-add-badges-and-cdnMichel Weststratebefore adoption227e953
line 14why, one step back14Fixed typo and yarn.lockMichel Weststratebefore adoption101aac2
line 15why, one step back15Immer (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 16why, one step back16It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 17why, one step back17Readme improvementsMichel Weststratebefore adoption58e9b57
line 18why, one step back18The 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 19why, one step back19Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state.Readme improvementsMichel Weststratebefore adoption58e9b57
line 20why, one step back20This 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 21why, one step back21Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
line 22why, one step back22Doc improvementsMichel Weststratebefore adoptiona3fcf04
line 23why, one step back23`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 24why, one step back24Using 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 25why, one step back25Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 26why, one step back26A 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 27–29why, one step back2728## API29Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 30why, one step back30The Immer package exposes a default function that does all the work.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 31why, one step back31`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 32why, one step back32`produce(currentState, producer: (draftState) => void): nextState`Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 33why, one step back33Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 34–35why, one step back34There is also a curried overload that is explained [below](#currying)35Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 36–38why, one step back36## Example3738```javascript`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 39why, one step back39import produce from "immer"Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
line 40why, one step back40Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 41–46why, one step back41const baseState = [42 {43 todo: "Learn typescript",44 done: true45 },46 {Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 47why, one step back47 todo: "Try immer",Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 48–51why, one step back48 done: false49 }50]51`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 52why, one step back52const nextState = produce(baseState, draftState => {Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 53–54why, one step back53 draftState.push({ todo: "Tweet about it" })54 draftState[1].done = trueFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 55–57why, one step back55})56```57Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 58why, one step back58The 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 59–74why, one step back5960```javascript61// the new item is only added to the next state,62// base state is unmodified63expect(baseState.length).toBe(2)64expect(nextState.length).toBe(3)6566// same for the changed 'done' prop67expect(baseState[1].done).toBe(false)68expect(nextState[1].done).toBe(true)6970// unchanged data is structurally shared71expect(nextState[0]).toBe(baseState[0])72// changed data not (dûh)73expect(nextState[1]).not.toBe(baseState[1])74```Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 75–77why, one step back7576## Benefits77Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 78–83why, one step back78* Immutability with normal JavaScript objects and arrays. No new APIs to learn!79* Strongly typed, no string based paths selectors etc.80* Structural sharing out of the box81* Object freezing out of the box82* Deep updates are a breeze83* Boilerplate reduction. Less noise, more concise code.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 84why, one step back84Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 85why, one step back85Read further to see all these benefits explained.Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 86why, one step back86Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 87–88why, one step back87## Reducer Example88Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 89why, one step back89Here is a simple example of the difference that Immer could make in practice.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 90–91why, one step back9091```javascriptMerge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 92–94why, one step back92// Redux reducer93// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js94const byId = (state, action) => {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 95why, one step back95 switch (action.type) {Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 96why, one step back96 case RECEIVE_PRODUCTS:Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 97–98why, one step back97 return {98 ...state,Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 99–102why, one step back99 ...action.products.reduce((obj, product) => {100 obj[product.id] = product101 return obj102 }, {})Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 103–109why, one step back103 }104 default:105 return state106 }107}108```109Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 110why, one step back110After using Immer, that simply becomes:Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 111–112why, one step back111112```javascript`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 113why, one step back113import produce from 'immer'Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 114why, one step back114Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 115–116why, one step back115const byId = (state, action) =>116 produce(state, draft => {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 117why, one step back117 switch (action.type) {Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 118–120why, one step back118 case RECEIVE_PRODUCTS:119 action.products.forEach(product => {120 draft[product.id] = productFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 121–125why, one step back121 })122 }123 })124```125transpile es5 codeMichel Weststratebefore adoptionf012154
line 126why, one step back126Notice 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 127why, one step back127transpile es5 codeMichel Weststratebefore adoptionf012154
line 128why, one step back128Creating Redux reducer is just a sample application of the Immer package.Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 129why, one step back129Immer is not just designed to simplify Redux reducers.transpile es5 codeMichel Weststratebefore adoptionf012154
lines 130–132why, one step back130It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).131132_Note: it might be tempting after using producers a while, to just put `produce` in your root reducer, and then past the draft along to each reducer and work on that. Don't do that. It kills the point of Redux where each reducer is testable as pure reducer. Immer is best used when applying it to small individual pieces of logic._Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b
line 133why, one step back133Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 134–155why, one step back134## Currying135136`produce` can be called with one or two arguments.137The one argument version is intended to be used as currying. This means that you get a pre-pound producer, that only needs a state to produce the value from.138The producer function get's passed in the draft, and any further arguments that were passed to the curried function.139140For example:141142```javascript143// mapper will be of signature (state, index) => state144const mapper = produce((draft, index) => {145 draft.index = index146})147148// example usage149console.dir([{}, {}, {}].map(mapper))150//[{index: 0}, {index: 1}, {index: 2}])151```152153This mechanism can also nicely be leveraged to further simplify our example reducer:154155```javascriptFixed configurability of array.length on proxies. Fixes #50Michel Weststratebefore adoption1c7df26
lines 156–157why, one step back156import produce from 'immer'157Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 158–192why, one step back158const byId = produce((draft, action) => {159 switch (action.type) {160 case RECEIVE_PRODUCTS:161 action.products.forEach(product => {162 draft[product.id] = product163 })164 }165})166```167168Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).169One think to keep in mind; you cannot use this construction to initialize an uninitialized state. E.g. `draft = {}` doesn't do anything useful.170171172## Auto freezing173174 Immer automatically freezes any state trees that are modified using `produce`.175 This protects against accidental modifications of the state tree outside of a producer.176 This comes with a performance impact, so it is recommended to disable this option in production.177 It is by default enabled.178 Use `setAutoFreeze(true / false)` to turn this feature on or off.179180## Using Immer on older JavaScript environments181182By default `produce` tries to use proxies for optimal performance.183However, on older JavaScript engines `Proxy` is not available.184For example, Microsoft Internet Explorer or React Native on Android.185In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:186187```javascript188import immer from "immer/es5"189```190191## More reducer examples192`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 193why, one step back193Here are some typical reducer examples, take from the Redux [Immutable Update Patterns](https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) page, and their Immer counter part.Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b
lines 194–207why, one step back194These examples are semantically equivalent and produce the exact same state.195196```javascript197// Plain reducer198function insertItem(array, action) {199 return [200 ...array.slice(0, action.index),201 action.item,202 ...array.slice(action.index)203 ]204}205206// With immer207function insertItem(array, action) {`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 208why, one step back208 return produce(array, draft => {Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b
lines 209–222why, one step back209 draft.splice(action.index, 0, action.item)210 })211}212213// Plain reducer214function removeItem(array, action) {215 return [216 ...array.slice(0, action.index),217 ...array.slice(action.index + 1)218 ];219}220221// With immer222function removeItem(array, action) {`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 223why, one step back223 return produce(array, draft => {Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b
lines 224–234why, one step back224 draft.splice(action.index, 1)225 })226}227228// Plain reducer229function updateObjectInArray(array, action) {230 return array.map( (item, index) => {231 if(index !== action.index) {232 // This isn't the item we care about - keep it as-is233 return item;234 }Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 235why, one step back235Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b
lines 236–245why, one step back236 // Otherwise, this is the one we want - return an updated value237 return {238 ...item,239 ...action.item240 };241 });242}243244// With immer245function updateObjectInArray(array, action) {`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 246why, one step back246 return produce(array, draft => {Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b
line 247why, one step back247 draft[action.index] = { ...item, ...action.item}Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 248why, one step back248 // Alternatively, since arbitrarily deep updates are supported:Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b
lines 249–253why, one step back249 // Object.assign(draft[action.index], action.item)250 })251}252```253Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 254why, one step back254## PitfallsFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 255why, one step back255Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 256why, one step back256* Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.Readme improvementsMichel Weststratebefore adoptiona1f5c6a
line 257why, one step back257* Immer only processes native arrays and plain objects (with a prototype of `null` or `Object`). Any other type of value will be treated verbatim! So if you modify a `Map` or `Buffer` or whatever complex object from the draft state, it will be that very same object in both the base state as the next state. In such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
line 258why, one step back258* Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`Readme improvementsMichel Weststratebefore adoptiona1f5c6a
line 259why, one step back259* 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 260why, one step back260Merge pull request #37 from mweststrate/feature/curryMichel Weststratebefore adoption014019e
lines 261–264why, one step back261## How does Immer work?262263Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/9d73d8f71cb3).264Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 265–266why, one step back265## Performance266`immer` -> `produce`. Implements #24Michel Weststratebefore adoptione3eacea
line 267why, one step back267Here is a [simple benchmark](__tests__/performance.js) on the performance of Immer.Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 268–273why, one step back268This test takes 100.000 todo items, and updates 10.000 of them.269_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.270271These tests were executed on Node 8.4.0.272Use `yarn test:perf` to reproduce them locally.273Fixed performance imagesMichel Weststratebefore adoption89e0d24
line 274why, one step back274Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 275–277why, one step back275276Some observations:277* 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 278why, one step back278* 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 279why, one step back279* 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 280why, one step back280* 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 281why, one step back281* 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 282why, one step back282* The peeks in the _frozen_ versions of _just mutate_, _deepclone_ and _naive reducer_ come from the fact that they recursively freeze the full state tree, while the other test cases only freeze the modified parts of the tree.Added performance measurements, fixes #6Michel Weststratebefore adoption553299f
lines 283–286why, one step back283284## Credits285286Special 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 287–290why, one step back287288## Donations289290A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)