readme.md
This file
Path
readme.md
777 lines · 30.6 KiB · Markdown
Last changed by
docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56
History of this fileTake it
The walk stopped after 200 commits: lines older than 84229e2 point at it.
Picked a logoMichel Weststratebefore adoptionf1ca2f6
lines 1–2why, one step back1<img src="images/immer-logo.png" height="200px" align="right"/>2updated changelogMichel Weststratebefore adoption84229e2
lines 3–4why, one step back3# Immer4Merge pull request #156 from styfle/patch-1Michel Weststratebefore adoptione0a8a1a
line 5why, one step back5[](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)Picked a logoMichel Weststratebefore adoptionf1ca2f6
line 6why, one step back6updated changelogMichel Weststratebefore adoption84229e2
lines 7–8why, one step back7_Create the next immutable state tree by simply modifying the current tree_8chore: add "Release notes" link to readmealeclarsonbefore adoption1803dd8
lines 9–10why, one step back9### [Release notes](https://github.com/mweststrate/immer/releases)10More readme linksMichel Weststratebefore adoptiond4a165b
line 11why, one step back11Did 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 12why, one step back12updated changelogMichel Weststratebefore adoption84229e2
lines 13–14why, one step back13---14chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 15–19why, one step back15- NPM: `npm install immer`16- Yarn: `yarn add immer`17- CDN: Exposed global is `immer`18 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`19 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`updated changelogMichel Weststratebefore adoption84229e2
lines 20–22why, one step back2021---22chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 23–24why, one step back23- 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)24- Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)updated changelogMichel Weststratebefore adoption84229e2
lines 25–27why, one step back2526Immer (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.27Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 28why, one step back28The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_. 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.updated changelogMichel Weststratebefore adoption84229e2
lines 29–31why, one step back293031Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 32why, one step back32Using 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).updated changelogMichel Weststratebefore adoption84229e2
lines 33–35why, one step back3334A 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.35Added some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 36–37why, one step back36## External resources37chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 38–42why, one step back38- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)39- 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)40- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)41- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)42- [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 43why, one step back43- [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 44why, one step back44updated changelogMichel Weststratebefore adoption84229e2
lines 45–94why, one step back45## API4647The Immer package exposes a default function that does all the work.4849`produce(currentState, producer: (draftState) => void): nextState`5051There is also a curried overload that is explained [below](#currying).5253## Example5455```javascript56import produce from "immer"5758const baseState = [59 {60 todo: "Learn typescript",61 done: true62 },63 {64 todo: "Try immer",65 done: false66 }67]6869const nextState = produce(baseState, draftState => {70 draftState.push({todo: "Tweet about it"})71 draftState[1].done = true72})73```7475The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.7677```javascript78// the new item is only added to the next state,79// base state is unmodified80expect(baseState.length).toBe(2)81expect(nextState.length).toBe(3)8283// same for the changed 'done' prop84expect(baseState[1].done).toBe(false)85expect(nextState[1].done).toBe(true)8687// unchanged data is structurally shared88expect(nextState[0]).toBe(baseState[0])89// changed data not (dûh)90expect(nextState[1]).not.toBe(baseState[1])91```9293## Benefits94chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 95–100why, one step back95- Immutability with normal JavaScript objects and arrays. No new APIs to learn!96- Strongly typed, no string based paths selectors etc.97- Structural sharing out of the box98- Object freezing out of the box99- Deep updates are a breeze100- Boilerplate reduction. Less noise, more concise code.docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 101why, one step back101- Small [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)updated changelogMichel Weststratebefore adoption84229e2
lines 102–181why, one step back102103Read further to see all these benefits explained.104105## Reducer Example106107Here is a simple example of the difference that Immer could make in practice.108109```javascript110// Redux reducer111// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js112const byId = (state, action) => {113 switch (action.type) {114 case RECEIVE_PRODUCTS:115 return {116 ...state,117 ...action.products.reduce((obj, product) => {118 obj[product.id] = product119 return obj120 }, {})121 }122 default:123 return state124 }125}126```127128After using Immer, that simply becomes:129130```javascript131import produce from "immer"132133const byId = (state, action) =>134 produce(state, draft => {135 switch (action.type) {136 case RECEIVE_PRODUCTS:137 action.products.forEach(product => {138 draft[product.id] = product139 })140 }141 })142```143144Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.145146Creating 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).147148_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._149150## React.setState example151152Deep 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)):153154```javascript155/**156 * Classic React.setState with a deep merge157 */158onBirthDayClick1 = () => {159 this.setState(prevState => ({160 user: {161 ...prevState.user,162 age: prevState.user.age + 1163 }164 }))165}166167/**168 * ...But, since setState accepts functions,169 * we can just create a curried producer and further simplify!170 */171onBirthDayClick2 = () => {172 this.setState(173 produce(draft => {174 draft.user.age += 1175 })176 )177}178```179180## Currying181Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 182why, one step back182Passing 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.updated changelogMichel Weststratebefore adoption84229e2
lines 183–234why, one step back183184For example:185186```javascript187// mapper will be of signature (state, index) => state188const mapper = produce((draft, index) => {189 draft.index = index190})191192// example usage193console.dir([{}, {}, {}].map(mapper))194//[{index: 0}, {index: 1}, {index: 2}])195```196197This mechanism can also nicely be leveraged to further simplify our example reducer:198199```javascript200import produce from 'immer'201202const byId = produce((draft, action) => {203 switch (action.type) {204 case RECEIVE_PRODUCTS:205 action.products.forEach(product => {206 draft[product.id] = product207 })208 return209 })210 }211})212```213214Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).215216If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:217218```javascript219import produce from "immer"220221const byId = produce(222 (draft, action) => {223 switch (action.type) {224 case RECEIVE_PRODUCTS:225 action.products.forEach(product => {226 draft[product.id] = product227 })228 return229 }230 },231 {232 1: {id: 1, name: "product-1"}233 }234)Added some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 235–238why, one step back235```236237##### Fun with currying238chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 239why, one step back239A 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 240–246why, one step back240241```javascript242import produce from "immer"243const spread = produce(Object.assign)244245const base = {x: 1, y: 1}246chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 247why, one step back247console.log({...base, y: 1} === base) // falseAdded some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 248–249why, one step back248console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced249console.log(spread(base, {y: 2}) === base) // false, produced a new object as it shouldupdated changelogMichel Weststratebefore adoption84229e2
lines 250–251why, one step back250```251Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 252–253why, one step back252## Patches253chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 254why, one step back254During 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.Update readmeMichel Weststratebefore adoption341cfeb
lines 255–257why, one step back255256Patches are useful in few scenarios:257chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 258–260why, one step back258- To exchange incremental updates with other parties, for example over websockets259- For debugging / traces, to see precisely how state is changed over time260- As basis for undo/redo or as an approach to replay changes on a slightly different state treeMerge branch 'patches'Michel Weststratebefore adoption2513fb8
line 261why, one step back261chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 262–263why, one step back262To 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:263Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 264–272why, one step back264```javascript265import produce, {applyPatches} from "immer"266267let state = {268 name: "Micheal",269 age: 32270}271272// Let's assume the user is in a wizard, and we don't know whetherSpell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 273why, one step back273// his changes should end up in the base state ultimately or not...Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 274–291why, one step back274let fork = state275// all the changes the user made in the wizard276let changes = []277// the inverse of all the changes made in the wizard278let inverseChanges = []279280fork = produce(281 fork,282 draft => {283 draft.age = 33284 },285 // The third argument to produce is a callback to which the patches will be fed286 (patches, inversePatches) => {287 changes.push(...patches)288 inverseChanges.push(...inversePatches)289 }290)291Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 292why, one step back292// In the meantime, our original state is replaced, as, for example,Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 293–303why, one step back293// some changes were received from the server294state = produce(state, draft => {295 draft.name = "Michel"296})297298// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!299state = applyPatches(state, changes)300301// state now contains the changes from both code paths!302expect(state).toEqual({303 name: "Michel", // changed by the serverchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 304why, one step back304 age: 33 // changed by the wizardMerge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 305–310why, one step back305})306307// Finally, even after finishing the wizard, the user might change his mind and undo his changes...308state = applyPatches(state, inverseChanges)309expect(state).toEqual({310 name: "Michel", // Not revertedchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 311why, one step back311 age: 32 // RevertedMerge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 312–314why, one step back312})313```314chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 315why, one step back315The 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 branch 'patches'Michel Weststratebefore adoption2513fb8
lines 316–318why, one step back316317```json318[chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 319–324why, one step back319 {320 "op": "replace",321 "path": ["profile"],322 "value": {"name": "Veria", "age": 5}323 },324 {"op": "remove", "path": ["tags", 3]}Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 325–329why, one step back325]326```327328```json329[chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 330–331why, one step back330 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},331 {"op": "add", "path": ["tags", 3], "value": "kiddo"}Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 332–334why, one step back332]333```334Added link to immer patch articleMichel Weststratebefore adoption255d135
lines 335–336why, one step back335For 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)336Added note about compressing patchesMichel Weststratebefore adoption7cae55b
lines 337–338why, one step back337Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.338Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 339why, one step back339## Async producersupdated changelogMichel Weststratebefore adoption84229e2
line 340why, one step back340Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 341why, one step back341It 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:updated changelogMichel Weststratebefore adoption84229e2
line 342why, one step back342Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 343–351why, one step back343```javascript344import produce from "immer"345346const user = {347 name: "michel",348 todos: []349}350351const loadedUser = await produce(user, async function(draft) {docs: fixed error in docsMichel Weststratebefore adoption42b14bd
line 352why, one step back352 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 353–378why, one step back353})354```355356_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._357358## `createDraft` and `finishDraft`359360`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:361362```javascript363import {createDraft, finishDraft} from "immer"364365const user = {366 name: "michel",367 todos: []368}369370const draft = createDraft(user)371draft.todos = await (await window.fetch("http://host/" + draft.name)).json()372const loadedUser = finishDraft(draft)373```374375Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.376377_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._378updated changelogMichel Weststratebefore adoption84229e2
lines 379–419why, one step back379## Returning data from producers380381It 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`.382383It 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:384385```javascript386const userReducer = produce((draft, action) => {387 switch (action.type) {388 case "renameUser":389 // OK: we modify the current state390 draft.users[action.payload.id].name = action.payload.name391 return draft // same as just 'return'392 case "loadUsers":393 // OK: we return an entirely new state394 return action.payload395 case "adduser-1":396 // NOT OK: This doesn't do change the draft nor return a new state!397 // It doesn't modify the draft (it just redeclares it)398 // In fact, this just doesn't do anything at all399 draft = {users: [...draft.users, action.payload]}400 return401 case "adduser-2":402 // NOT OK: modifying draft *and* returning a new state403 draft.userCount += 1404 return {users: [...draft.users, action.payload]}405 case "adduser-3":406 // OK: returning a new state. But, unnecessary complex and expensive407 return {408 userCount: draft.userCount + 1,409 users: [...draft.users, action.payload]410 }411 case "adduser-4":412 // OK: the immer way413 draft.userCount += 1414 draft.users.push(action.payload)415 return416 }417})418```419Merge pull request #197 from 0xflotus/patch-1Michel Weststratebefore adoption21ad96b
line 420why, one step back420_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 421why, one step back421Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 422–423why, one step back422## Producing `undefined` using `nothing`423chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 424why, one step back424So, 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 425–440why, one step back425426```javascript427produce({}, draft => {428 // don't do anything429})430```431432Versus:433434```javascript435produce({}, draft => {436 // Try to return undefined from the producer437 return undefined438})439```440chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 441why, one step back441The 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 442–445why, one step back442443However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:444445```javascriptchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 446why, one step back446import produce, {nothing} from "immer"Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 447–451why, one step back447448const state = {449 hello: "world"450}451chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 452–453why, one step back452produce(state, draft => {})453produce(state, draft => undefined)Less is moreMichel Weststratebefore adoption1802421
line 454why, one step back454// Both return the original state: { hello: "world"}Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
line 455why, one step back455chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 456why, one step back456produce(state, draft => nothing)Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 457–461why, one step back457// Produces a new state, 'undefined'458```459460N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.461Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 462–477why, one step back462## Inline shortcuts using `void`463464Draft 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.465466In 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`.467468```javascript469// Single mutation470produce(draft => void (draft.user.age += 1))471472// Multiple mutations473produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))474```475476Code 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.477Merge pull request #179 from RichieAHB/rahb/add-originalMichel Weststratebefore adoptionf8479c2
lines 478–482why, one step back478## Extracting the original object from a proxied instance479480Immer 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.481482```jschore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 483why, one step back483const baseState = {users: [{name: "Richie"}]}Merge pull request #179 from RichieAHB/rahb/add-originalMichel Weststratebefore adoptionf8479c2
lines 484–488why, one step back484const nextState = produce(baseState, draftState => {485 original(draftState.users) // is === baseState.users486})487```488Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
lines 489–491why, one step back489Just want to know if a value is a proxied instance? Use the `isDraft` function!490491```jschore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 492why, one step back492import {isDraft} from "immer"Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 493why, one step back493chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 494why, one step back494const baseState = {users: [{name: "Bobby"}]}Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 495why, one step back495const nextState = produce(baseState, draft => {chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 496–497why, one step back496 isDraft(draft) // => true497 isDraft(draft.users) // => trueMerge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
lines 498–502why, one step back498 isDraft(draft.users[0]) // => true499})500isDraft(nextState) // => false501```502Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 503why, one step back503## Auto freezingupdated changelogMichel Weststratebefore adoption84229e2
line 504why, one step back504Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 505why, one step back505Immer 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.updated changelogMichel Weststratebefore adoption84229e2
lines 506–508why, one step back506507## Immer on older JavaScript environments?508Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 509why, one step back509By 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.updated changelogMichel Weststratebefore adoption84229e2
line 510why, one step back510`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015
lines 511–512why, one step back511## Importing immer512Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 513why, one step back513`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:`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015
lines 514–516why, one step back514515```javascript516import produce from "immer"chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 517why, one step back517import {produce} from "immer"`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015
line 518why, one step back518chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 519why, one step back519const {produce} = require("immer")`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015
lines 520–523why, one step back520const produce = require("immer").produce521const produce = require("immer").default522523import unleashTheMagic from "immer"chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 524why, one step back524import {produce as unleashTheMagic} from "immer"`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015
lines 525–526why, one step back525```526docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 527why, one step back527## Supported object typesupdated changelogMichel Weststratebefore adoption84229e2
line 528why, one step back528docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56
lines 529–545why, one step back529Plain objects and arrays are always drafted by Immer.530531Every 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.532533```js534import {immerable} from 'immer'535536class Foo {537 [immerable] = true // Option 1538539 constructor() {540 this[immerable] = true // Option 2541 }542}543544Foo[immerable] = true // Option 3545```chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 546why, one step back546docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 547why, one step back547For 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 548why, one step back548docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 549why, one step back549When 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 550why, one step back550docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 551why, one step back551Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 552why, one step back552docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 553why, one step back553```jsAdded some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 554why, one step back554const state = {docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 555–556why, one step back555 set: new Set(),556 map: new Map()Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
lines 557–558why, one step back557}558const nextState = produce(state, draft => {docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 559–560why, one step back559 // Don't use any Set methods, as that mutates the instance!560 draft.set.add("foo") // ❌Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 561why, one step back561docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 562–563why, one step back562 // 1. Instead, clone the set (just once)563 const newSet = new Set(draft.set) // ✅Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 564why, one step back564docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 565–566why, one step back565 // 2. Mutate the clone (just in this producer)566 newSet.add("foo")Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 567why, one step back567docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 568–569why, one step back568 // 3. Update the draft with the new set569 draft.set = newSetAdded some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 570why, one step back570docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 571–581why, one step back571 // Similarly, don't use any Map methods.572 draft.map.set("foo", "bar") // ❌573574 // 1. Instead, clone the map (just once)575 const newMap = new Map(draft.map) // ✅576577 // 2. Mutate it578 newMap.set("foo", "bar")579580 // 3. Update the draft581 draft.map = newMapAdded some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
lines 582–583why, one step back582})583```docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 584why, one step back584Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 585–637why, one step back585## TypeScript or Flow586587The 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.588589The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:590591```ts592import produce from "immer"593594interface State {595 readonly x: number596}597598// `x` cannot be modified here599const state: State = {600 x: 0601}602603const newState = produce<State>(state, draft => {604 // `x` can be modified here605 draft.x++606})607608// `newState.x` cannot be modified here609```610611This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!612613**Note:** Immer v1.9+ supports Typescript v3.1+ only.614615## Using `this`616617_Deprecated, this will probably be removed in a next major version, see [#308](https://github.com/mweststrate/immer/issues/308)_618619The recipe will be always invoked with the `draft` as `this` context.620621This means that the following constructions are also valid:622623```javascript624const base = {counter: 0}625626const next = produce(base, function() {627 this.counter++628})629console.log(next.counter) // 1630631// OR632const increment = produce(function() {633 this.counter++634})635console.log(increment(base).counter) // 1636```637docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 638–645why, one step back638# Pitfalls6396401. 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).6411. 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.6421. 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.6431. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.6441. 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)})`6451. 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.Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 646why, one step back646updated changelogMichel Weststratebefore adoption84229e2
lines 647–648why, one step back647## Cool things built with immer648chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 649–656why, one step back649- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_650- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_651- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_652- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_653- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_654- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_655- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_656- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_Merge pull request #285 from epeli/patch-1Michel Weststratebefore adoptionaf55671
line 657why, one step back657- [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 658why, one step back658- [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 659why, one step back659- [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 660why, one step back660- ... and [many more](https://www.npmjs.com/browse/depended/immer)updated changelogMichel Weststratebefore adoption84229e2
lines 661–719why, one step back661662## How does Immer work?663664Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).665666## Example patterns.667668_For those who have to go back to thinking in object updates :-)_669670```javascript671import produce from "immer"672673// object mutations674const todosObj = {675 id1: {done: false, body: "Take out the trash"},676 id2: {done: false, body: "Check Email"}677}678679// add680const addedTodosObj = produce(todosObj, draft => {681 draft["id3"] = {done: false, body: "Buy bananas"}682})683684// delete685const deletedTodosObj = produce(todosObj, draft => {686 delete draft["id1"]687})688689// update690const updatedTodosObj = produce(todosObj, draft => {691 draft["id1"].done = true692})693694// array mutations695const todosArray = [696 {id: "id1", done: false, body: "Take out the trash"},697 {id: "id2", done: false, body: "Check Email"}698]699700// add701const addedTodosArray = produce(todosArray, draft => {702 draft.push({id: "id3", done: false, body: "Buy bananas"})703})704705// delete706const deletedTodosArray = produce(todosArray, draft => {707 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)708 // or (slower):709 // return draft.filter(todo => todo.id !== "id1")710})711712// update713const updatedTodosArray = produce(todosArray, draft => {714 draft[draft.findIndex(todo => todo.id === "id1")].done = true715})716```717718## Performance719Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 720why, one step back720Here 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.updated changelogMichel Weststratebefore adoption84229e2
line 721why, one step back721Update readmeMichel Weststratebefore adoption341cfeb
line 722why, one step back722These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.updated changelogMichel Weststratebefore adoption84229e2
lines 723–725why, one step back723724725Update readmeMichel Weststratebefore adoption341cfeb
line 726why, one step back726Most important observation:updated changelogMichel Weststratebefore adoption84229e2
line 727why, one step back727chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 728–731why, one step back728- 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.729- 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)730- Generating patches doesn't significantly slow immer down731- 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 732–737why, one step back732733## Migration734735**Immer 1.\* -> 2.0**736737Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.updated changelogMichel Weststratebefore adoption84229e2
lines 738–772why, one step back738739## FAQ740741_(for those who skimmed the above instead of actually reading)_742743**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**744745A: Yes746747**Q: Does Immer support deep updates?**748749A: Yes750751**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**752753A: Yes754755**Q: Can I typecheck my data structures when using Immer?**756757A: Yes758759**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**760761A: Yes762763**Q: Is it fast?**764765A: Yes766767**Q: Idea! Can Immer freeze the state for me?**768769A: Yes770771## Credits772Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 773why, one step back773Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.updated changelogMichel Weststratebefore adoption84229e2
lines 774–777why, one step back774775## Donations776777A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)