readme.md
This file
Path
readme.md
779 lines · 30.7 KiB · Markdown
Last changed by
Update readme.md (#334)Noitidartbefore adoptionab7a44b
History of this fileTake it
The walk stopped after 200 commits: lines older than d6d0f69 point at it.
Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 1–8why, one step back1<img src="images/immer-logo.png" height="200px" align="right"/>23# Immer45[](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)67_Create the next immutable state tree by simply modifying the current tree_8[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653
lines 9–10why, one step back9Winner of the "breakthrough of the year" [open source award](https://osawards.com/react/) in 201910chore: add "Release notes" link to readmealeclarsonbefore adoption1803dd8
lines 11–12why, one step back11### [Release notes](https://github.com/mweststrate/immer/releases)12More readme linksMichel Weststratebefore adoptiond4a165b
line 13why, one step back13Did Immer make a difference to your project? Consider buying me a coffee!<br/><a href="https://www.buymeacoffee.com/mweststrate" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: auto !important;width: auto !important;" ></a>added some readme clarificationsMichel Weststratebefore adoption897c284
line 14why, one step back14Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 15–16why, one step back15---16chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 17–21why, one step back17- NPM: `npm install immer`18- Yarn: `yarn add immer`19- CDN: Exposed global is `immer`20 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`21 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 22–24why, one step back2223---24chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 25–26why, one step back25- 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)26- Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 27–29why, one step back2728Immer (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.29Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 30why, one step back30The 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.Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 31–33why, one step back313233Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
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).Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 35–37why, one step back3536A 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.37Added some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 38–39why, one step back38## External resources39chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 40–44why, one step back40- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)41- Blog: by Workday Prism on why they picked Immer to manage immutable state [The Search for a Strongly-Typed, Immutable State](https://medium.com/workday-engineering/workday-prism-analytics-the-search-for-a-strongly-typed-immutable-state-a09f6768b2b5)42- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)43- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)44- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststratedocs: added ForwardJS talk by swyxMichel Weststratebefore adoption984434e
line 45why, one step back45- [ForwardJS 2019: Immutability is Changing - From Immutable.js to Immer](https://www.youtube.com/watch?v=bFuRvcAEiHg&feature=youtu.be) by [shawn swyx wang](https://twitter.com/swyx/)Added some external resources to readmeMichel Weststratebefore adoptionc018c49
line 46why, one step back46Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 47–96why, one step back47## API4849The Immer package exposes a default function that does all the work.5051`produce(currentState, producer: (draftState) => void): nextState`5253There is also a curried overload that is explained [below](#currying).5455## Example5657```javascript58import produce from "immer"5960const baseState = [61 {62 todo: "Learn typescript",63 done: true64 },65 {66 todo: "Try immer",67 done: false68 }69]7071const nextState = produce(baseState, draftState => {72 draftState.push({todo: "Tweet about it"})73 draftState[1].done = true74})75```7677The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.7879```javascript80// the new item is only added to the next state,81// base state is unmodified82expect(baseState.length).toBe(2)83expect(nextState.length).toBe(3)8485// same for the changed 'done' prop86expect(baseState[1].done).toBe(false)87expect(nextState[1].done).toBe(true)8889// unchanged data is structurally shared90expect(nextState[0]).toBe(baseState[0])91// changed data not (dûh)92expect(nextState[1]).not.toBe(baseState[1])93```9495## Benefits96chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 97–102why, one step back97- Immutability with normal JavaScript objects and arrays. No new APIs to learn!98- Strongly typed, no string based paths selectors etc.99- Structural sharing out of the box100- Object freezing out of the box101- Deep updates are a breeze102- Boilerplate reduction. Less noise, more concise code.docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 103why, one step back103- Small [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 104–183why, one step back104105Read further to see all these benefits explained.106107## Reducer Example108109Here is a simple example of the difference that Immer could make in practice.110111```javascript112// Redux reducer113// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js114const byId = (state, action) => {115 switch (action.type) {116 case RECEIVE_PRODUCTS:117 return {118 ...state,119 ...action.products.reduce((obj, product) => {120 obj[product.id] = product121 return obj122 }, {})123 }124 default:125 return state126 }127}128```129130After using Immer, that simply becomes:131132```javascript133import produce from "immer"134135const byId = (state, action) =>136 produce(state, draft => {137 switch (action.type) {138 case RECEIVE_PRODUCTS:139 action.products.forEach(product => {140 draft[product.id] = product141 })142 }143 })144```145146Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.147148Creating 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).149150_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._151152## React.setState example153154Deep 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)):155156```javascript157/**158 * Classic React.setState with a deep merge159 */160onBirthDayClick1 = () => {161 this.setState(prevState => ({162 user: {163 ...prevState.user,164 age: prevState.user.age + 1165 }166 }))167}168169/**170 * ...But, since setState accepts functions,171 * we can just create a curried producer and further simplify!172 */173onBirthDayClick2 = () => {174 this.setState(175 produce(draft => {176 draft.user.age += 1177 })178 )179}180```181182## Currying183Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 184why, one step back184Passing 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 #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 185–236why, one step back185186For example:187188```javascript189// mapper will be of signature (state, index) => state190const mapper = produce((draft, index) => {191 draft.index = index192})193194// example usage195console.dir([{}, {}, {}].map(mapper))196//[{index: 0}, {index: 1}, {index: 2}])197```198199This mechanism can also nicely be leveraged to further simplify our example reducer:200201```javascript202import produce from 'immer'203204const byId = produce((draft, action) => {205 switch (action.type) {206 case RECEIVE_PRODUCTS:207 action.products.forEach(product => {208 draft[product.id] = product209 })210 return211 })212 }213})214```215216Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).217218If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:219220```javascript221import produce from "immer"222223const byId = produce(224 (draft, action) => {225 switch (action.type) {226 case RECEIVE_PRODUCTS:227 action.products.forEach(product => {228 draft[product.id] = product229 })230 return231 }232 },233 {234 1: {id: 1, name: "product-1"}235 }236)Added some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 237–240why, one step back237```238239##### Fun with currying240chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 241why, one step back241A random fun example just for inspiration: a neat trick is to turn `Object.assign` into a producer to create a "spread" function that is smarter than the normal spread operator, as it doesn't produce a new state if the result doesn't actually change ([details & explanation](https://twitter.com/mweststrate/status/1045059430256119809)). Quick example:Added some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 242–248why, one step back242243```javascript244import produce from "immer"245const spread = produce(Object.assign)246247const base = {x: 1, y: 1}248chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 249why, one step back249console.log({...base, y: 1} === base) // falseAdded some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 250–251why, one step back250console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced251console.log(spread(base, {y: 2}) === base) // false, produced a new object as it shouldMerge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 252–255why, one step back252```253254## Patches255chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 256why, one step back256During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer. This is a very powerful tool if you want to fork your state temporarily and replay the changes to the original.Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 257–259why, one step back257258Patches are useful in few scenarios:259chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 260–262why, one step back260- To exchange incremental updates with other parties, for example over websockets261- For debugging / traces, to see precisely how state is changed over time262- As basis for undo/redo or as an approach to replay changes on a slightly different state treeMerge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 263why, one step back263chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 264–265why, one step back264To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used to record the incremental updates and (inverse) apply them:265Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 266–274why, one step back266```javascript267import produce, {applyPatches} from "immer"268269let state = {270 name: "Micheal",271 age: 32272}273274// Let's assume the user is in a wizard, and we don't know whetherSpell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 275why, one step back275// his changes should end up in the base state ultimately or not...Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 276–293why, one step back276let fork = state277// all the changes the user made in the wizard278let changes = []279// the inverse of all the changes made in the wizard280let inverseChanges = []281282fork = produce(283 fork,284 draft => {285 draft.age = 33286 },287 // The third argument to produce is a callback to which the patches will be fed288 (patches, inversePatches) => {289 changes.push(...patches)290 inverseChanges.push(...inversePatches)291 }292)293Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 294why, one step back294// In the meantime, our original state is replaced, as, for example,Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 295–305why, one step back295// some changes were received from the server296state = produce(state, draft => {297 draft.name = "Michel"298})299300// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!301state = applyPatches(state, changes)302303// state now contains the changes from both code paths!304expect(state).toEqual({305 name: "Michel", // changed by the serverchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 306why, one step back306 age: 33 // changed by the wizardMerge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 307–312why, one step back307})308309// Finally, even after finishing the wizard, the user might change his mind and undo his changes...310state = applyPatches(state, inverseChanges)311expect(state).toEqual({312 name: "Michel", // Not revertedchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 313why, one step back313 age: 32 // RevertedMerge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 314–316why, one step back314})315```316chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 317why, one step back317The generated patches are similar (but not the same) to the [RFC-6902 JSON patch standard](http://tools.ietf.org/html/rfc6902), except that the `path` property is an array, rather than a string. This makes processing patches easier. If you want to normalize to the official specification, `patch.path = patch.path.join("/")` should do the trick. Anyway, this is what a bunch of patches and their inverse could look like:Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 318–320why, one step back318319```json320[chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 321–326why, one step back321 {322 "op": "replace",323 "path": ["profile"],324 "value": {"name": "Veria", "age": 5}325 },326 {"op": "remove", "path": ["tags", 3]}Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 327–331why, one step back327]328```329330```json331[chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 332–333why, one step back332 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},333 {"op": "add", "path": ["tags", 3], "value": "kiddo"}Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 334–336why, one step back334]335```336Added link to immer patch articleMichel Weststratebefore adoption255d135
lines 337–338why, one step back337For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)338Added note about compressing patchesMichel Weststratebefore adoption7cae55b
lines 339–340why, one step back339Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.340Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 341why, one step back341## Async producersMerge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 342why, one step back342Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 343why, one step back343It is allowed to return Promise objects from recipes. Or, in other words, to use `async / await`. This can be pretty useful for long running processes, that only produce the new object once the promise chain resolves. Note that `produce` itself (even in the curried form) will return a promise if the producer is async. Example:Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 344why, one step back344Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 345–353why, one step back345```javascript346import produce from "immer"347348const user = {349 name: "michel",350 todos: []351}352353const loadedUser = await produce(user, async function(draft) {docs: fixed error in docsMichel Weststratebefore adoption42b14bd
line 354why, one step back354 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 355–380why, one step back355})356```357358_Warning: please note that the draft shouldn't be 'leaked' from the async process and stored else where. The draft will still be revoked as soon as the async process completes._359360## `createDraft` and `finishDraft`361362`createDraft` and `finishDraft` are two low-level functions that are mostly useful for libraries that build abstractions on top of immer. It avoids the need to always create a function in order to work with drafts. Instead, one can create a draft, modify it, and at some time in the future finish the draft, in which case the next immutable state will be produced. We could for example rewrite our above example as:363364```javascript365import {createDraft, finishDraft} from "immer"366367const user = {368 name: "michel",369 todos: []370}371372const draft = createDraft(user)373draft.todos = await (await window.fetch("http://host/" + draft.name)).json()374const loadedUser = finishDraft(draft)375```376377Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.378379_Warning: in general, we recommend to use `produce` instead of the `createDraft` / `finishDraft` combo, `produce` is less error prone in usage, and more clearly separates the concepts of mutability and immutability in your code base._380Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 381–421why, one step back381## Returning data from producers382383It 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`.384385It 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:386387```javascript388const userReducer = produce((draft, action) => {389 switch (action.type) {390 case "renameUser":391 // OK: we modify the current state392 draft.users[action.payload.id].name = action.payload.name393 return draft // same as just 'return'394 case "loadUsers":395 // OK: we return an entirely new state396 return action.payload397 case "adduser-1":398 // NOT OK: This doesn't do change the draft nor return a new state!399 // It doesn't modify the draft (it just redeclares it)400 // In fact, this just doesn't do anything at all401 draft = {users: [...draft.users, action.payload]}402 return403 case "adduser-2":404 // NOT OK: modifying draft *and* returning a new state405 draft.userCount += 1406 return {users: [...draft.users, action.payload]}407 case "adduser-3":408 // OK: returning a new state. But, unnecessary complex and expensive409 return {410 userCount: draft.userCount + 1,411 users: [...draft.users, action.payload]412 }413 case "adduser-4":414 // OK: the immer way415 draft.userCount += 1416 draft.users.push(action.payload)417 return418 }419})420```421Merge pull request #197 from 0xflotus/patch-1Michel Weststratebefore adoption21ad96b
line 422why, one step back422_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._added some readme clarificationsMichel Weststratebefore adoption897c284
line 423why, one step back423Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 424–425why, one step back424## Producing `undefined` using `nothing`425chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 426why, one step back426So, in general, one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft. There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 427–442why, one step back427428```javascript429produce({}, draft => {430 // don't do anything431})432```433434Versus:435436```javascript437produce({}, draft => {438 // Try to return undefined from the producer439 return undefined440})441```442chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 443why, one step back443The problem is that in JavaScript a function that doesn't return anything also returns `undefined`! So immer cannot differentiate between those different cases. So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 444–447why, one step back444445However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:446447```javascriptchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 448why, one step back448import produce, {nothing} from "immer"Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 449–453why, one step back449450const state = {451 hello: "world"452}453chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 454–455why, one step back454produce(state, draft => {})455produce(state, draft => undefined)Less is moreMichel Weststratebefore adoption1802421
line 456why, one step back456// Both return the original state: { hello: "world"}Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
line 457why, one step back457chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 458why, one step back458produce(state, draft => nothing)Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 459–463why, one step back459// Produces a new state, 'undefined'460```461462N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.463Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 464–479why, one step back464## Inline shortcuts using `void`465466Draft mutations in Immer usually warrant a code block, since a return denotes an overwrite. Sometimes that can stretch code a little more than you might be comfortable with.467468In such cases, you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.469470```javascript471// Single mutation472produce(draft => void (draft.user.age += 1))473474// Multiple mutations475produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))476```477478Code style is highly personal, but for code bases that are to be understood by many, we recommend to stick to the classic `draft => { draft.user.age += 1}` to avoid cognitive overhead.479Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 480–484why, one step back480## Extracting the original object from a proxied instance481482Immer exposes a named export `original` that will get the original object from the proxied instance inside `produce` (or return `undefined` for unproxied values). A good example of when this can be useful is when searching for nodes in a tree-like state using strict equality.483484```jschore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 485why, one step back485const baseState = {users: [{name: "Richie"}]}Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 486–490why, one step back486const nextState = produce(baseState, draftState => {487 original(draftState.users) // is === baseState.users488})489```490Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
lines 491–493why, one step back491Just want to know if a value is a proxied instance? Use the `isDraft` function!492493```jschore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 494why, one step back494import {isDraft} from "immer"Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 495why, one step back495chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 496why, one step back496const baseState = {users: [{name: "Bobby"}]}Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 497why, one step back497const nextState = produce(baseState, draft => {chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 498–499why, one step back498 isDraft(draft) // => true499 isDraft(draft.users) // => trueMerge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
lines 500–504why, one step back500 isDraft(draft.users[0]) // => true501})502isDraft(nextState) // => false503```504Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 505why, one step back505## Auto freezingMerge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 506why, one step back506Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 507why, one step back507Immer 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 #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 508–510why, one step back508509## Immer on older JavaScript environments?510Update readme.md (#334)Noitidartbefore adoptionab7a44b
line 511why, one step back511By 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 (< v0.59) on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 512–514why, one step back512513## Importing immer514Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 515why, one step back515`produce` is exposed as the default export, but optionally it can be used as name import as well, as this benefits some older project setups. So the following imports are all correct, where the first is recommended:Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 516–518why, one step back516517```javascript518import produce from "immer"chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 519why, one step back519import {produce} from "immer"Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 520why, one step back520chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 521why, one step back521const {produce} = require("immer")Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 522–525why, one step back522const produce = require("immer").produce523const produce = require("immer").default524525import unleashTheMagic from "immer"chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 526why, one step back526import {produce as unleashTheMagic} from "immer"Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 527–528why, one step back527```528docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 529why, one step back529## Supported object typesMerge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 530why, one step back530docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56
lines 531–535why, one step back531Plain objects and arrays are always drafted by Immer.532533Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.534535```js[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653
line 536why, one step back536import {immerable} from "immer"docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56
lines 537–538why, one step back537538class Foo {[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653
line 539why, one step back539 [immerable] = true // Option 1docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56
line 540why, one step back540[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653
lines 541–543why, one step back541 constructor() {542 this[immerable] = true // Option 2543 }docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56
lines 544–547why, one step back544}545546Foo[immerable] = true // Option 3547```chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 548why, one step back548docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 549why, one step back549For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.Improved the readme concerning limitations. Fixes #185Michel Weststratebefore adoptionf0e8c47
line 550why, one step back550docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 551why, one step back551When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.Improved the readme concerning limitations. Fixes #185Michel Weststratebefore adoptionf0e8c47
line 552why, one step back552docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 553why, one step back553Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 554why, one step back554docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 555why, one step back555```jsMerge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 556why, one step back556const state = {docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 557–558why, one step back557 set: new Set(),558 map: new Map()Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 559–560why, one step back559}560const nextState = produce(state, draft => {docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 561–562why, one step back561 // Don't use any Set methods, as that mutates the instance!562 draft.set.add("foo") // ❌Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 563why, one step back563docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 564–565why, one step back564 // 1. Instead, clone the set (just once)565 const newSet = new Set(draft.set) // ✅Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 566why, one step back566docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 567–568why, one step back567 // 2. Mutate the clone (just in this producer)568 newSet.add("foo")Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 569why, one step back569docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 570–571why, one step back570 // 3. Update the draft with the new set571 draft.set = newSetMerge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
line 572why, one step back572docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 573–583why, one step back573 // Similarly, don't use any Map methods.574 draft.map.set("foo", "bar") // ❌575576 // 1. Instead, clone the map (just once)577 const newMap = new Map(draft.map) // ✅578579 // 2. Mutate it580 newMap.set("foo", "bar")581582 // 3. Update the draft583 draft.map = newMapMerge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 584–585why, one step back584})585```docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 586why, one step back586Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 587–639why, one step back587## TypeScript or Flow588589The 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.590591The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:592593```ts594import produce from "immer"595596interface State {597 readonly x: number598}599600// `x` cannot be modified here601const state: State = {602 x: 0603}604605const newState = produce<State>(state, draft => {606 // `x` can be modified here607 draft.x++608})609610// `newState.x` cannot be modified here611```612613This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!614615**Note:** Immer v1.9+ supports Typescript v3.1+ only.616617## Using `this`618619_Deprecated, this will probably be removed in a next major version, see [#308](https://github.com/mweststrate/immer/issues/308)_620621The recipe will be always invoked with the `draft` as `this` context.622623This means that the following constructions are also valid:624625```javascript626const base = {counter: 0}627628const next = produce(base, function() {629 this.counter++630})631console.log(next.counter) // 1632633// OR634const increment = produce(function() {635 this.counter++636})637console.log(increment(base).counter) // 1638```639docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 640–647why, one step back640# Pitfalls6416421. 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).6431. Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, and there should be no circular references.6441. 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`. Also, realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.6451. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.6461. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`6471. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 648–650why, one step back648649## Cool things built with immer650chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 651–658why, one step back651- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_652- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_653- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_654- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_655- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_656- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_657- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_658- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_Merge pull request #285 from epeli/patch-1Michel Weststratebefore adoptionaf55671
line 659why, one step back659- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse Redux reducers with Typescript_docs: add redux-ts-utils to "cool things made with immer"Kenneth Powersbefore adoption0b6960a
line 660why, one step back660- [redux-ts-utils](https://github.com/knpwrs/redux-ts-utils) _Everything you need to create type-safe applications with Redux with a strong emphasis on simplicity_docs: add react-state-treeAlec Larsonbefore adoptiondfcd543
line 661why, one step back661- [react-state-tree](https://github.com/suchipi/react-state-tree) _Drop-in replacement for useState that persists your state into a redux-like state tree_chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 662why, one step back662- ... and [many more](https://www.npmjs.com/browse/depended/immer)Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 663–721why, one step back663664## How does Immer work?665666Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).667668## Example patterns.669670_For those who have to go back to thinking in object updates :-)_671672```javascript673import produce from "immer"674675// object mutations676const todosObj = {677 id1: {done: false, body: "Take out the trash"},678 id2: {done: false, body: "Check Email"}679}680681// add682const addedTodosObj = produce(todosObj, draft => {683 draft["id3"] = {done: false, body: "Buy bananas"}684})685686// delete687const deletedTodosObj = produce(todosObj, draft => {688 delete draft["id1"]689})690691// update692const updatedTodosObj = produce(todosObj, draft => {693 draft["id1"].done = true694})695696// array mutations697const todosArray = [698 {id: "id1", done: false, body: "Take out the trash"},699 {id: "id2", done: false, body: "Check Email"}700]701702// add703const addedTodosArray = produce(todosArray, draft => {704 draft.push({id: "id3", done: false, body: "Buy bananas"})705})706707// delete708const deletedTodosArray = produce(todosArray, draft => {709 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)710 // or (slower):711 // return draft.filter(todo => todo.id !== "id1")712})713714// update715const updatedTodosArray = produce(todosArray, draft => {716 draft[draft.findIndex(todo => todo.id === "id1")].done = true717})718```719720## Performance721Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 722why, one step back722Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 50,000 todo items and updates 5,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 #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 723–729why, one step back723724These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.725726727728Most important observation:729chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 730–733why, one step back730- Immer with proxies is roughly speaking twice to three times slower as a handwritten reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.731- 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)732- Generating patches doesn't significantly slow immer down733- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 734–739why, one step back734735## Migration736737**Immer 1.\* -> 2.0**738739Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 740–774why, one step back740741## FAQ742743_(for those who skimmed the above instead of actually reading)_744745**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**746747A: Yes748749**Q: Does Immer support deep updates?**750751A: Yes752753**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**754755A: Yes756757**Q: Can I typecheck my data structures when using Immer?**758759A: Yes760761**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**762763A: Yes764765**Q: Is it fast?**766767A: Yes768769**Q: Idea! Can Immer freeze the state for me?**770771A: Yes772773## Credits774Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 775why, one step back775Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.Merge pull request #186 from arilotter/patch-1Michel Weststratebefore adoptiond6d0f69
lines 776–779why, one step back776777## Donations778779A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)