readme.md
This file
Path
readme.md
278 lines · 10.7 KiB · Markdown
Last changed by
Fixed #49Michel Weststratebefore adoption5227173
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
lines 7–8why, one step back78Updated changelogMichel Weststratebefore adoption8f44348
line 9why, one step back9_Create the next immutable state tree by simply modifying the current tree_Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 10–12why, one step back1011---12Readme cleanupMichel Weststratebefore adoptiona3b49ff
lines 13–14why, one step back13* NPM / Yarn: `npm install immer`14* CDN: https://unpkg.com/immerMerge pull request #39 from fkhadra/issue-7-add-badges-and-cdnMichel Weststratebefore adoption227e953
line 15why, one step back15Fixed typo and yarn.lockMichel Weststratebefore adoption101aac2
line 16why, one step back16Immer (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 17why, one step back17It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 18why, one step back18Readme improvementsMichel Weststratebefore adoption58e9b57
lines 19–21why, one step back19The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.20Once all your mutations are completed, immer will produce the _nextState_ based on the mutations to the draft state.21This 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 22why, one step back22Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
line 23why, one step back23Doc improvementsMichel Weststratebefore adoptiona3fcf04
line 24why, one step back24Merge pull request #17 from mattruby/patch-1Michel Weststratebefore adoption8432c1b
line 25why, one step back25Using 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
lines 26–27why, one step back2627A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applicable to plain, native JavaScript data structures (arrays and objects) without further needing any library.Doc improvementsMichel Weststratebefore adoptiona3fcf04
line 28why, one step back28Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
lines 29–32why, one step back29## Installation3031`npm install immer`32Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 33–34why, one step back33## API34Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 35–36why, one step back35The immer package exposes a single function:36Doc improvementsMichel Weststratebefore adoptiona3fcf04
line 37why, one step back37`immer(currentState, fn: (draftState) => void): nextState`Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 38–41why, one step back3839## Example4041```javascriptMerge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
lines 42–43why, one step back42import immer from "immer"43Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 44–54why, one step back44const baseState = [45 {46 todo: "Learn typescript",47 done: true48 },49 {50 todo: "Try immer",51 done: false52 }53]54Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 55–57why, one step back55const nextState = immer(baseState, draftState => {56 draftState.push({ todo: "Tweet about it" })57 draftState[1].done = trueFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 58–60why, one step back58})59```60Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
line 61why, one step back61The 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 62–77why, one step back6263```javascript64// the new item is only added to the next state,65// base state is unmodified66expect(baseState.length).toBe(2)67expect(nextState.length).toBe(3)6869// same for the changed 'done' prop70expect(baseState[1].done).toBe(false)71expect(nextState[1].done).toBe(true)7273// unchanged data is structurally shared74expect(nextState[0]).toBe(baseState[0])75// changed data not (dûh)76expect(nextState[1]).not.toBe(baseState[1])77```Doc improvementsMichel Weststratebefore adoptiona3fcf04
line 78why, one step back78Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
lines 79–89why, one step back79## Using immer on older JavaScript environments8081By default `immer` tries to use proxies for optimal performance.82However, on older JavaScript engines `Proxy` is not available.83For example, Microsoft Internet Explorer or React Native on Android.84In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:8586```javascript87import immer from "immer/es5"88```89Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 90–92why, one step back90## Benefits9192* Use the language© to construct create your next stateMerge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
lines 93–94why, one step back93* Use JavaScript native arrays and object94* Automatic immutability; any state tree produced by `immer` will by defualt be deeply frozenDoc improvementsMichel Weststratebefore adoptiona3fcf04
lines 95–97why, one step back95* Strongly typed, no string based paths etc96* Deep updates are trivial97* Small, dependency free library with minimal api surfaceMerge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f
line 98why, one step back98* No accidental mutations of current state, but intentional mutations of a draft stateFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 99why, one step back99Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 100–108why, one step back100## Auto freezing101102 Immer automatically freezes any state trees that are modified using `immer.103 This protects against accidental modifications of the state tree outside of an immer function.104 This comes with a performance impact, so it is recommended to disable this option in production.105 It is by default enabled.106107 Use `setAutoFreeze(true / false)` to turn this feature on or off.108Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 109–110why, one step back109## Reducer Example110Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
line 111why, one step back111Here is a simple example of the difference that this approach could make in practice.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 112–113why, one step back112The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)113Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
line 114why, one step back114_Note, this 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)_Disclaimer: not just reduxMichel Weststratebefore adoption0574ae0
line 115why, one step back115Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 116–161why, one step back116```javascript117const todo = (state, action) => {118 switch (action.type) {119 case 'ADD_TODO':120 return {121 id: action.id,122 text: action.text,123 completed: false124 }125 case 'TOGGLE_TODO':126 if (state.id !== action.id) {127 return state128 }129130 return {131 ...state,132 completed: !state.completed133 }134 default:135 return state136 }137}138139const todos = (state = [], action) => {140 switch (action.type) {141 case 'ADD_TODO':142 return [143 ...state,144 todo(undefined, action)145 ]146 case 'TOGGLE_TODO':147 return state.map(t =>148 todo(t, action)149 )150 default:151 return state152 }153}154```155156After using immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):157158```javascript159import immer from 'immer'160161const todos = (state = [], action) =>readme improvementsMichel Weststratebefore adoptionc674cad
lines 162–163why, one step back162 // immer produces nextState from draftState and returns it163 immer(state, draftState => {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 164–165why, one step back164 switch (action.type) {165 case 'ADD_TODO':readme improvementsMichel Weststratebefore adoptionc674cad
line 166why, one step back166 draftState.push({Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 167–172why, one step back167 id: action.id,168 text: action.text,169 completed: false170 })171 return172 case 'TOGGLE_TODO':readme improvementsMichel Weststratebefore adoptionc674cad
line 173why, one step back173 const todo = draftState.find(todo => todo.id === action.id)Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 174–179why, one step back174 todo.completed = !todo.completed175 return176 }177 })178```179Merge pull request #17 from mattruby/patch-1Michel Weststratebefore adoption8432c1b
line 180why, one step back180Creating middleware or a reducer wrapper that applies `immer` automatically is left as exercise for the reader :-).Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 181why, one step back181Added examples from the Redux Update Patterns PageMichel Weststratebefore adoptionda3a08b
lines 182–244why, one step back182---183184Here 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.185These examples are semantically equivalent and produce the exact same state.186187```javascript188// Plain reducer189function insertItem(array, action) {190 return [191 ...array.slice(0, action.index),192 action.item,193 ...array.slice(action.index)194 ]195}196197// With immer198function insertItem(array, action) {199 return immer(array, draft => {200 draft.splice(action.index, 0, action.item)201 })202}203204// Plain reducer205function removeItem(array, action) {206 return [207 ...array.slice(0, action.index),208 ...array.slice(action.index + 1)209 ];210}211212// With immer213function removeItem(array, action) {214 return immer(array, draft => {215 draft.splice(action.index, 1)216 })217}218219// Plain reducer220function updateObjectInArray(array, action) {221 return array.map( (item, index) => {222 if(index !== action.index) {223 // This isn't the item we care about - keep it as-is224 return item;225 }226227 // Otherwise, this is the one we want - return an updated value228 return {229 ...item,230 ...action.item231 };232 });233}234235// With immer236function updateObjectInArray(array, action) {237 return immer(array, draft => {238 draft[action.index] = { ...item, ...action.item}239 // Alternatively, since arbitrarily deep updates are supported:240 // Object.assign(draft[action.index], action.item)241 })242}243```244Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 245–246why, one step back245## Limitations246Merge pull request #17 from mattruby/patch-1Michel Weststratebefore adoption8432c1b
lines 247–248why, one step back247* Currently, only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)248* Currently, only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 249–251why, one step back249250## Pitfalls:251Readme improvementsMichel Weststratebefore adoptiona1f5c6a
line 252why, one step back252* 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 branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
lines 253–254why, one step back253* Make sure to modify the draft state you get passed in in the callback function, not the original current state that was passed as the first argument to `immer`!254* Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the `immer` block or read from the `currentState` rather than the `draftState`Readme improvementsMichel Weststratebefore adoptiona1f5c6a
line 255why, one step back255* 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
lines 256–265why, one step back256257## Performance258259Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.260This test takes 100.000 todo items, and updates 10.000 of them.261_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.262263These tests were executed on Node 8.4.0.264Use `yarn test:perf` to reproduce them locally.265Fixed performance imagesMichel Weststratebefore adoption89e0d24
line 266why, one step back266Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 267–269why, one step back267268Some observations:269* 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).Fixed #49Michel Weststratebefore adoption5227173
lines 270–271why, one step back270* The _reduce_ 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.271* 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 272why, one step back272* 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)Fixed #49Michel Weststratebefore adoption5227173
line 273why, one step back273* 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 274why, one step back274* 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 275–278why, one step back275276## Credits277278Special 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.