readme.md
This file
Path
readme.md
758 lines · 30.0 KiB · Markdown
Last changed by
docs: fixed error in docsMichel Weststratebefore adoption42b14bd
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 WeststrateAdded some external resources to readmeMichel Weststratebefore adoptionc018c49
line 43why, one step back43updated changelogMichel Weststratebefore adoption84229e2
lines 44–93why, one step back44## API4546The Immer package exposes a default function that does all the work.4748`produce(currentState, producer: (draftState) => void): nextState`4950There is also a curried overload that is explained [below](#currying).5152## Example5354```javascript55import produce from "immer"5657const baseState = [58 {59 todo: "Learn typescript",60 done: true61 },62 {63 todo: "Try immer",64 done: false65 }66]6768const nextState = produce(baseState, draftState => {69 draftState.push({todo: "Tweet about it"})70 draftState[1].done = true71})72```7374The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.7576```javascript77// the new item is only added to the next state,78// base state is unmodified79expect(baseState.length).toBe(2)80expect(nextState.length).toBe(3)8182// same for the changed 'done' prop83expect(baseState[1].done).toBe(false)84expect(nextState[1].done).toBe(true)8586// unchanged data is structurally shared87expect(nextState[0]).toBe(baseState[0])88// changed data not (dûh)89expect(nextState[1]).not.toBe(baseState[1])90```9192## Benefits93chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 94–99why, one step back94- Immutability with normal JavaScript objects and arrays. No new APIs to learn!95- Strongly typed, no string based paths selectors etc.96- Structural sharing out of the box97- Object freezing out of the box98- Deep updates are a breeze99- Boilerplate reduction. Less noise, more concise code.docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 100why, one step back100- Small [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)updated changelogMichel Weststratebefore adoption84229e2
lines 101–180why, one step back101102Read further to see all these benefits explained.103104## Reducer Example105106Here is a simple example of the difference that Immer could make in practice.107108```javascript109// Redux reducer110// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js111const byId = (state, action) => {112 switch (action.type) {113 case RECEIVE_PRODUCTS:114 return {115 ...state,116 ...action.products.reduce((obj, product) => {117 obj[product.id] = product118 return obj119 }, {})120 }121 default:122 return state123 }124}125```126127After using Immer, that simply becomes:128129```javascript130import produce from "immer"131132const byId = (state, action) =>133 produce(state, draft => {134 switch (action.type) {135 case RECEIVE_PRODUCTS:136 action.products.forEach(product => {137 draft[product.id] = product138 })139 }140 })141```142143Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.144145Creating 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).146147_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._148149## React.setState example150151Deep 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)):152153```javascript154/**155 * Classic React.setState with a deep merge156 */157onBirthDayClick1 = () => {158 this.setState(prevState => ({159 user: {160 ...prevState.user,161 age: prevState.user.age + 1162 }163 }))164}165166/**167 * ...But, since setState accepts functions,168 * we can just create a curried producer and further simplify!169 */170onBirthDayClick2 = () => {171 this.setState(172 produce(draft => {173 draft.user.age += 1174 })175 )176}177```178179## Currying180Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 181why, one step back181Passing 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 182–233why, one step back182183For example:184185```javascript186// mapper will be of signature (state, index) => state187const mapper = produce((draft, index) => {188 draft.index = index189})190191// example usage192console.dir([{}, {}, {}].map(mapper))193//[{index: 0}, {index: 1}, {index: 2}])194```195196This mechanism can also nicely be leveraged to further simplify our example reducer:197198```javascript199import produce from 'immer'200201const byId = produce((draft, action) => {202 switch (action.type) {203 case RECEIVE_PRODUCTS:204 action.products.forEach(product => {205 draft[product.id] = product206 })207 return208 })209 }210})211```212213Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).214215If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:216217```javascript218import produce from "immer"219220const byId = produce(221 (draft, action) => {222 switch (action.type) {223 case RECEIVE_PRODUCTS:224 action.products.forEach(product => {225 draft[product.id] = product226 })227 return228 }229 },230 {231 1: {id: 1, name: "product-1"}232 }233)Added some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 234–237why, one step back234```235236##### Fun with currying237chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 238why, one step back238A 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 239–245why, one step back239240```javascript241import produce from "immer"242const spread = produce(Object.assign)243244const base = {x: 1, y: 1}245chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 246why, one step back246console.log({...base, y: 1} === base) // falseAdded some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 247–248why, one step back247console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced248console.log(spread(base, {y: 2}) === base) // false, produced a new object as it shouldupdated changelogMichel Weststratebefore adoption84229e2
lines 249–250why, one step back249```250Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 251–252why, one step back251## Patches252chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 253why, one step back253During 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 254–256why, one step back254255Patches are useful in few scenarios:256chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 257–259why, one step back257- To exchange incremental updates with other parties, for example over websockets258- For debugging / traces, to see precisely how state is changed over time259- As basis for undo/redo or as an approach to replay changes on a slightly different state treeMerge branch 'patches'Michel Weststratebefore adoption2513fb8
line 260why, one step back260chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 261–262why, one step back261To 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:262Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 263–271why, one step back263```javascript264import produce, {applyPatches} from "immer"265266let state = {267 name: "Micheal",268 age: 32269}270271// Let's assume the user is in a wizard, and we don't know whetherSpell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 272why, one step back272// his changes should end up in the base state ultimately or not...Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 273–290why, one step back273let fork = state274// all the changes the user made in the wizard275let changes = []276// the inverse of all the changes made in the wizard277let inverseChanges = []278279fork = produce(280 fork,281 draft => {282 draft.age = 33283 },284 // The third argument to produce is a callback to which the patches will be fed285 (patches, inversePatches) => {286 changes.push(...patches)287 inverseChanges.push(...inversePatches)288 }289)290Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 291why, one step back291// In the meantime, our original state is replaced, as, for example,Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 292–302why, one step back292// some changes were received from the server293state = produce(state, draft => {294 draft.name = "Michel"295})296297// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!298state = applyPatches(state, changes)299300// state now contains the changes from both code paths!301expect(state).toEqual({302 name: "Michel", // changed by the serverchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 303why, one step back303 age: 33 // changed by the wizardMerge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 304–309why, one step back304})305306// Finally, even after finishing the wizard, the user might change his mind and undo his changes...307state = applyPatches(state, inverseChanges)308expect(state).toEqual({309 name: "Michel", // Not revertedchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 310why, one step back310 age: 32 // RevertedMerge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 311–313why, one step back311})312```313chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 314why, one step back314The 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 315–317why, one step back315316```json317[chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 318–323why, one step back318 {319 "op": "replace",320 "path": ["profile"],321 "value": {"name": "Veria", "age": 5}322 },323 {"op": "remove", "path": ["tags", 3]}Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 324–328why, one step back324]325```326327```json328[chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 329–330why, one step back329 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},330 {"op": "add", "path": ["tags", 3], "value": "kiddo"}Merge branch 'patches'Michel Weststratebefore adoption2513fb8
lines 331–333why, one step back331]332```333Added link to immer patch articleMichel Weststratebefore adoption255d135
lines 334–335why, one step back334For 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)335Added note about compressing patchesMichel Weststratebefore adoption7cae55b
lines 336–337why, one step back336Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.337Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 338why, one step back338## Async producersupdated changelogMichel Weststratebefore adoption84229e2
line 339why, one step back339Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 340why, one step back340It 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 341why, one step back341Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 342–350why, one step back342```javascript343import produce from "immer"344345const user = {346 name: "michel",347 todos: []348}349350const loadedUser = await produce(user, async function(draft) {docs: fixed error in docsMichel Weststratebefore adoption42b14bd
line 351why, one step back351 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 352–377why, one step back352})353```354355_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._356357## `createDraft` and `finishDraft`358359`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:360361```javascript362import {createDraft, finishDraft} from "immer"363364const user = {365 name: "michel",366 todos: []367}368369const draft = createDraft(user)370draft.todos = await (await window.fetch("http://host/" + draft.name)).json()371const loadedUser = finishDraft(draft)372```373374Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.375376_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._377updated changelogMichel Weststratebefore adoption84229e2
lines 378–418why, one step back378## Returning data from producers379380It 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`.381382It 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:383384```javascript385const userReducer = produce((draft, action) => {386 switch (action.type) {387 case "renameUser":388 // OK: we modify the current state389 draft.users[action.payload.id].name = action.payload.name390 return draft // same as just 'return'391 case "loadUsers":392 // OK: we return an entirely new state393 return action.payload394 case "adduser-1":395 // NOT OK: This doesn't do change the draft nor return a new state!396 // It doesn't modify the draft (it just redeclares it)397 // In fact, this just doesn't do anything at all398 draft = {users: [...draft.users, action.payload]}399 return400 case "adduser-2":401 // NOT OK: modifying draft *and* returning a new state402 draft.userCount += 1403 return {users: [...draft.users, action.payload]}404 case "adduser-3":405 // OK: returning a new state. But, unnecessary complex and expensive406 return {407 userCount: draft.userCount + 1,408 users: [...draft.users, action.payload]409 }410 case "adduser-4":411 // OK: the immer way412 draft.userCount += 1413 draft.users.push(action.payload)414 return415 }416})417```418Merge pull request #197 from 0xflotus/patch-1Michel Weststratebefore adoption21ad96b
line 419why, one step back419_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 420why, one step back420Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 421–422why, one step back421## Producing `undefined` using `nothing`422chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 423why, one step back423So, 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 424–439why, one step back424425```javascript426produce({}, draft => {427 // don't do anything428})429```430431Versus:432433```javascript434produce({}, draft => {435 // Try to return undefined from the producer436 return undefined437})438```439chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 440why, one step back440The 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 441–444why, one step back441442However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:443444```javascriptchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 445why, one step back445import produce, {nothing} from "immer"Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 446–450why, one step back446447const state = {448 hello: "world"449}450chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 451–452why, one step back451produce(state, draft => {})452produce(state, draft => undefined)Less is moreMichel Weststratebefore adoption1802421
line 453why, one step back453// Both return the original state: { hello: "world"}Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
line 454why, one step back454chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 455why, one step back455produce(state, draft => nothing)Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
lines 456–460why, one step back456// Produces a new state, 'undefined'457```458459N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.460Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 461–476why, one step back461## Inline shortcuts using `void`462463Draft 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.464465In 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`.466467```javascript468// Single mutation469produce(draft => void (draft.user.age += 1))470471// Multiple mutations472produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))473```474475Code 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.476Merge pull request #179 from RichieAHB/rahb/add-originalMichel Weststratebefore adoptionf8479c2
lines 477–481why, one step back477## Extracting the original object from a proxied instance478479Immer 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.480481```jschore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 482why, one step back482const baseState = {users: [{name: "Richie"}]}Merge pull request #179 from RichieAHB/rahb/add-originalMichel Weststratebefore adoptionf8479c2
lines 483–487why, one step back483const nextState = produce(baseState, draftState => {484 original(draftState.users) // is === baseState.users485})486```487Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
lines 488–490why, one step back488Just want to know if a value is a proxied instance? Use the `isDraft` function!489490```jschore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 491why, one step back491import {isDraft} from "immer"Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 492why, one step back492chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 493why, one step back493const baseState = {users: [{name: "Bobby"}]}Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 494why, one step back494const nextState = produce(baseState, draft => {chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 495–496why, one step back495 isDraft(draft) // => true496 isDraft(draft.users) // => trueMerge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
lines 497–501why, one step back497 isDraft(draft.users[0]) // => true498})499isDraft(nextState) // => false500```501Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 502why, one step back502## Auto freezingupdated changelogMichel Weststratebefore adoption84229e2
line 503why, one step back503Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 504why, one step back504Immer 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 505–507why, one step back505506## Immer on older JavaScript environments?507Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 508why, one step back508By 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 509why, one step back509`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015
lines 510–511why, one step back510## Importing immer511Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 512why, one step back512`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 513–515why, one step back513514```javascript515import produce from "immer"chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 516why, one step back516import {produce} from "immer"`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015
line 517why, one step back517chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 518why, one step back518const {produce} = require("immer")`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015
lines 519–522why, one step back519const produce = require("immer").produce520const produce = require("immer").default521522import unleashTheMagic from "immer"chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 523why, one step back523import {produce as unleashTheMagic} from "immer"`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015
lines 524–525why, one step back524```525docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 526why, one step back526## Supported object typesupdated changelogMichel Weststratebefore adoption84229e2
line 527why, one step back527docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 528why, one step back528Only plain objects and arrays are automatically drafted by Immer. This means other object types should never be mutated **unless** you added the exported `immerable` symbol to the object itself, its prototype, or its class constructor. In that case, the object is essentially an immutable plain object with a custom prototype.chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 529why, one step back529docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 530why, one step back530For 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 531why, one step back531docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 532why, one step back532When 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 533why, one step back533docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 534why, one step back534Built-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 535why, one step back535docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 536why, one step back536```jsAdded some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 537why, one step back537const state = {docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 538–539why, one step back538 set: new Set(),539 map: new Map()Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
lines 540–541why, one step back540}541const nextState = produce(state, draft => {docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 542–543why, one step back542 // Don't use any Set methods, as that mutates the instance!543 draft.set.add("foo") // ❌Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 544why, one step back544docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 545–546why, one step back545 // 1. Instead, clone the set (just once)546 const newSet = new Set(draft.set) // ✅Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 547why, one step back547docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 548–549why, one step back548 // 2. Mutate the clone (just in this producer)549 newSet.add("foo")Added some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 550why, one step back550docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 551–552why, one step back551 // 3. Update the draft with the new set552 draft.set = newSetAdded some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
line 553why, one step back553docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 554–564why, one step back554 // Similarly, don't use any Map methods.555 draft.map.set("foo", "bar") // ❌556557 // 1. Instead, clone the map (just once)558 const newMap = new Map(draft.map) // ✅559560 // 2. Mutate it561 newMap.set("foo", "bar")562563 // 3. Update the draft564 draft.map = newMapAdded some docs on how to use Immer together with Map or SetMichel Weststratebefore adoptiond9b4d56
lines 565–566why, one step back565})566```docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 567why, one step back567Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 568–620why, one step back568## TypeScript or Flow569570The 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.571572The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:573574```ts575import produce from "immer"576577interface State {578 readonly x: number579}580581// `x` cannot be modified here582const state: State = {583 x: 0584}585586const newState = produce<State>(state, draft => {587 // `x` can be modified here588 draft.x++589})590591// `newState.x` cannot be modified here592```593594This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!595596**Note:** Immer v1.9+ supports Typescript v3.1+ only.597598## Using `this`599600_Deprecated, this will probably be removed in a next major version, see [#308](https://github.com/mweststrate/immer/issues/308)_601602The recipe will be always invoked with the `draft` as `this` context.603604This means that the following constructions are also valid:605606```javascript607const base = {counter: 0}608609const next = produce(base, function() {610 this.counter++611})612console.log(next.counter) // 1613614// OR615const increment = produce(function() {616 this.counter++617})618console.log(increment(base).counter) // 1619```620docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 621–628why, one step back621# Pitfalls6226231. 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).6241. 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.6251. 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.6261. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.6271. 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)})`6281. 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 629why, one step back629updated changelogMichel Weststratebefore adoption84229e2
lines 630–631why, one step back630## Cool things built with immer631chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 632–639why, one step back632- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_633- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_634- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_635- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_636- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_637- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_638- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_639- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_Merge pull request #285 from epeli/patch-1Michel Weststratebefore adoptionaf55671
line 640why, one step back640- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse Redux reducers with Typescript_chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 641why, one step back641- ... and [many more](https://www.npmjs.com/browse/depended/immer)updated changelogMichel Weststratebefore adoption84229e2
lines 642–700why, one step back642643## How does Immer work?644645Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).646647## Example patterns.648649_For those who have to go back to thinking in object updates :-)_650651```javascript652import produce from "immer"653654// object mutations655const todosObj = {656 id1: {done: false, body: "Take out the trash"},657 id2: {done: false, body: "Check Email"}658}659660// add661const addedTodosObj = produce(todosObj, draft => {662 draft["id3"] = {done: false, body: "Buy bananas"}663})664665// delete666const deletedTodosObj = produce(todosObj, draft => {667 delete draft["id1"]668})669670// update671const updatedTodosObj = produce(todosObj, draft => {672 draft["id1"].done = true673})674675// array mutations676const todosArray = [677 {id: "id1", done: false, body: "Take out the trash"},678 {id: "id2", done: false, body: "Check Email"}679]680681// add682const addedTodosArray = produce(todosArray, draft => {683 draft.push({id: "id3", done: false, body: "Buy bananas"})684})685686// delete687const deletedTodosArray = produce(todosArray, draft => {688 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)689 // or (slower):690 // return draft.filter(todo => todo.id !== "id1")691})692693// update694const updatedTodosArray = produce(todosArray, draft => {695 draft[draft.findIndex(todo => todo.id === "id1")].done = true696})697```698699## Performance700Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 701why, one step back701Here 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 702why, one step back702Update readmeMichel Weststratebefore adoption341cfeb
line 703why, one step back703These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.updated changelogMichel Weststratebefore adoption84229e2
lines 704–706why, one step back704705706Update readmeMichel Weststratebefore adoption341cfeb
line 707why, one step back707Most important observation:updated changelogMichel Weststratebefore adoption84229e2
line 708why, one step back708chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 709–712why, one step back709- 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.710- 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)711- Generating patches doesn't significantly slow immer down712- 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 713–718why, one step back713714## Migration715716**Immer 1.\* -> 2.0**717718Make 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 719–753why, one step back719720## FAQ721722_(for those who skimmed the above instead of actually reading)_723724**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**725726A: Yes727728**Q: Does Immer support deep updates?**729730A: Yes731732**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**733734A: Yes735736**Q: Can I typecheck my data structures when using Immer?**737738A: Yes739740**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**741742A: Yes743744**Q: Is it fast?**745746A: Yes747748**Q: Idea! Can Immer freeze the state for me?**749750A: Yes751752## Credits753Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 754why, one step back754Special 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 755–758why, one step back755756## Donations757758A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)