Skip to content
Myr

WIP

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by Michel Weststrate · parent b1e2217 · Browse files · 8 files+820 added−910 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+820 added−910 removed

  • other:+820 added−910 removed

8 files+820 added−910 removed

modified:docs/doc1.md+807 added-11 removed
2 unmodified lines
3title: Latin-ish4sidebar_label: Example Page5---67Check the [documentation](https://docusaurus.io) for how to use Docusaurus.7- NPM: `npm install immer`8- Yarn: `yarn add immer`9- CDN: Exposed global is `immer`10 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`11 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`129## Lorem13---1411Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus elementum massa eget nulla aliquet sagittis. Proin odio tortor, vulputate ut odio in, ultrices ultricies augue. Cras ornare ultrices lorem malesuada iaculis. Etiam sit amet libero tempor, pulvinar mauris sed, sollicitudin sapien.15- 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)16- Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)1713## Mauris In Code18Immer (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.1920The basic idea is that you will apply all your changes to a temporary _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.2122![immer-hd.png](images/hd/immer.png)2324Using 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).2526A 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.2728## External resources2930- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)31- 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)32- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)33- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)34- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate35- [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/)3637## API3839The Immer package exposes a default function that does all the work.4041`produce(currentState, producer: (draftState) => void): nextState`4243There is also a curried overload that is explained [below](#currying).4445## Example4647```javascript48import produce from "immer"4950const baseState = [51 {52 todo: "Learn typescript",53 done: true54 },55 {56 todo: "Try immer",57 done: false58 }59]6061const nextState = produce(baseState, draftState => {62 draftState.push({todo: "Tweet about it"})63 draftState[1].done = true64})65```16Mauris vestibulum ullamcorper nibh, ut semper purus pulvinar ut. Donec volutpat orci sit amet mauris malesuada, non pulvinar augue aliquam. Vestibulum ultricies at urna ut suscipit. Morbi iaculis, erat at imperdiet semper, ipsum nulla sodales erat, eget tincidunt justo dui quis justo. Pellentesque dictum bibendum diam at aliquet. Sed pulvinar, dolor quis finibus ornare, eros odio facilisis erat, eu rhoncus nunc dui sed ex. Nunc gravida dui massa, sed ornare arcu tincidunt sit amet. Maecenas efficitur sapien neque, a laoreet libero feugiat ut.6667The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.6869```javascript70// the new item is only added to the next state,71// base state is unmodified72expect(baseState.length).toBe(2)73expect(nextState.length).toBe(3)7475// same for the changed 'done' prop76expect(baseState[1].done).toBe(false)77expect(nextState[1].done).toBe(true)7879// unchanged data is structurally shared80expect(nextState[0]).toBe(baseState[0])81// changed data not (dûh)82expect(nextState[1]).not.toBe(baseState[1])83```8419## Nulla85## Benefits8621Nulla facilisi. Maecenas sodales nec purus eget posuere. Sed sapien quam, pretium a risus in, porttitor dapibus erat. Sed sit amet fringilla ipsum, eget iaculis augue. Integer sollicitudin tortor quis ultricies aliquam. Suspendisse fringilla nunc in tellus cursus, at placerat tellus scelerisque. Sed tempus elit a sollicitudin rhoncus. Nulla facilisi. Morbi nec dolor dolor. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras et aliquet lectus. Pellentesque sit amet eros nisi. Quisque ac sapien in sapien congue accumsan. Nullam in posuere ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin lacinia leo a nibh fringilla pharetra.87- Immutability with normal JavaScript objects and arrays. No new APIs to learn!88- Strongly typed, no string based paths selectors etc.89- Structural sharing out of the box90- Object freezing out of the box91- Deep updates are a breeze92- Boilerplate reduction. Less noise, more concise code.93- Small [![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)9423## Orci95Read further to see all these benefits explained.9625Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin venenatis lectus dui, vel ultrices ante bibendum hendrerit. Aenean egestas feugiat dui id hendrerit. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur in tellus laoreet, eleifend nunc id, viverra leo. Proin vulputate non dolor vel vulputate. Curabitur pretium lobortis felis, sit amet finibus lorem suscipit ut. Sed non mollis risus. Duis sagittis, mi in euismod tincidunt, nunc mauris vestibulum urna, at euismod est elit quis erat. Phasellus accumsan vitae neque eu placerat. In elementum arcu nec tellus imperdiet, eget maximus nulla sodales. Curabitur eu sapien eget nisl sodales fermentum.97## Reducer Example9827## Phasellus99Here is a simple example of the difference that Immer could make in practice.10029Phasellus pulvinar ex id commodo imperdiet. Praesent odio nibh, sollicitudin sit amet faucibus id, placerat at metus. Donec vitae eros vitae tortor hendrerit finibus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque vitae purus dolor. Duis suscipit ac nulla et finibus. Phasellus ac sem sed dui dictum gravida. Phasellus eleifend vestibulum facilisis. Integer pharetra nec enim vitae mattis. Duis auctor, lectus quis condimentum bibendum, nunc dolor aliquam massa, id bibendum orci velit quis magna. Ut volutpat nulla nunc, sed interdum magna condimentum non. Sed urna metus, scelerisque vitae consectetur a, feugiat quis magna. Donec dignissim ornare nisl, eget tempor risus malesuada quis.101```javascript102// Redux reducer103// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js104const byId = (state, action) => {105 switch (action.type) {106 case RECEIVE_PRODUCTS:107 return {108 ...state,109 ...action.products.reduce((obj, product) => {110 obj[product.id] = product111 return obj112 }, {})113 }114 default:115 return state116 }117}118```119120After using Immer, that simply becomes:121122```javascript123import produce from "immer"124125const byId = (state, action) =>126 produce(state, draft => {127 switch (action.type) {128 case RECEIVE_PRODUCTS:129 action.products.forEach(product => {130 draft[product.id] = product131 })132 }133 })134```135136Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.137138Creating 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).139140_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._141142## React.setState example143144Deep 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)):145146```javascript147/**148 * Classic React.setState with a deep merge149 */150onBirthDayClick1 = () => {151 this.setState(prevState => ({152 user: {153 ...prevState.user,154 age: prevState.user.age + 1155 }156 }))157}158159/**160 * ...But, since setState accepts functions,161 * we can just create a curried producer and further simplify!162 */163onBirthDayClick2 = () => {164 this.setState(165 produce(draft => {166 draft.user.age += 1167 })168 )169}170```171172## Currying173174Passing 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.175176For example:177178```javascript179// mapper will be of signature (state, index) => state180const mapper = produce((draft, index) => {181 draft.index = index182})183184// example usage185console.dir([{}, {}, {}].map(mapper))186//[{index: 0}, {index: 1}, {index: 2}])187```188189This mechanism can also nicely be leveraged to further simplify our example reducer:190191```javascript192import produce from "immer"193194const byId = produce((draft, action) => {195 switch (action.type) {196 case RECEIVE_PRODUCTS:197 action.products.forEach(product => {198 draft[product.id] = product199 })200 return201 }202})203```204205Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).206207If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:208209```javascript210import produce from "immer"211212const byId = produce(213 (draft, action) => {214 switch (action.type) {215 case RECEIVE_PRODUCTS:216 action.products.forEach(product => {217 draft[product.id] = product218 })219 return220 }221 },222 {223 1: {id: 1, name: "product-1"}224 }225)226```227228##### Fun with currying229230A 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:231232```javascript233import produce from "immer"234const spread = produce(Object.assign)235236const base = {x: 1, y: 1}237238console.log({...base, y: 1} === base) // false239console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced240console.log(spread(base, {y: 2}) === base) // false, produced a new object as it should241```242243## Patches244245During 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.246247Patches are useful in few scenarios:248249- To exchange incremental updates with other parties, for example over websockets250- For debugging / traces, to see precisely how state is changed over time251- As basis for undo/redo or as an approach to replay changes on a slightly different state tree252253To 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:254255```javascript256import produce, {applyPatches} from "immer"257258let state = {259 name: "Micheal",260 age: 32261}262263// Let's assume the user is in a wizard, and we don't know whether264// his changes should end up in the base state ultimately or not...265let fork = state266// all the changes the user made in the wizard267let changes = []268// the inverse of all the changes made in the wizard269let inverseChanges = []270271fork = produce(272 fork,273 draft => {274 draft.age = 33275 },276 // The third argument to produce is a callback to which the patches will be fed277 (patches, inversePatches) => {278 changes.push(...patches)279 inverseChanges.push(...inversePatches)280 }281)282283// In the meantime, our original state is replaced, as, for example,284// some changes were received from the server285state = produce(state, draft => {286 draft.name = "Michel"287})288289// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!290state = applyPatches(state, changes)291292// state now contains the changes from both code paths!293expect(state).toEqual({294 name: "Michel", // changed by the server295 age: 33 // changed by the wizard296})297298// Finally, even after finishing the wizard, the user might change his mind and undo his changes...299state = applyPatches(state, inverseChanges)300expect(state).toEqual({301 name: "Michel", // Not reverted302 age: 32 // Reverted303})304```305306The 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:307308```json309[310 {311 "op": "replace",312 "path": ["profile"],313 "value": {"name": "Veria", "age": 5}314 },315 {"op": "remove", "path": ["tags", 3]}316]317```318319```json320[321 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},322 {"op": "add", "path": ["tags", 3], "value": "kiddo"}323]324```325326### `produceWithPatches`327328Instead of setting up a patch listener, an easier way to obtain the patches is to use `produceWithPatches`, which has the same signature as `produce`, except that it doesn't return just the next state, but a tuple consisting of `[nextState, patches, inversePatches]`. Like `produce`, `produceWithPatches` supports currying as well.329330```javascript331import {produceWithPatches} from "immer"332333const [nextState, patches, inversePatches] = produceWithPatches(334 {335 age: 33336 },337 draft => {338 draft.age++339 }340)341```342343Which produces:344345```javascript346;[347 {348 age: 34349 },350 [351 {352 op: "replace",353 path: ["age"],354 value: 34355 }356 ],357 [358 {359 op: "replace",360 path: ["age"],361 value: 33362 }363 ]364]365```366367For 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)368369Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.370371## Async producers372373It 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:374375```javascript376import produce from "immer"377378const user = {379 name: "michel",380 todos: []381}382383const loadedUser = await produce(user, async function(draft) {384 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()385})386```387388_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._389390## `createDraft` and `finishDraft`391392`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:393394```javascript395import {createDraft, finishDraft} from "immer"396397const user = {398 name: "michel",399 todos: []400}401402const draft = createDraft(user)403draft.todos = await (await window.fetch("http://host/" + draft.name)).json()404const loadedUser = finishDraft(draft)405```406407Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.408409_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._410411## Returning data from producers412413It 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`.414415It 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:416417```javascript418const userReducer = produce((draft, action) => {419 switch (action.type) {420 case "renameUser":421 // OK: we modify the current state422 draft.users[action.payload.id].name = action.payload.name423 return draft // same as just 'return'424 case "loadUsers":425 // OK: we return an entirely new state426 return action.payload427 case "adduser-1":428 // NOT OK: This doesn't do change the draft nor return a new state!429 // It doesn't modify the draft (it just redeclares it)430 // In fact, this just doesn't do anything at all431 draft = {users: [...draft.users, action.payload]}432 return433 case "adduser-2":434 // NOT OK: modifying draft *and* returning a new state435 draft.userCount += 1436 return {users: [...draft.users, action.payload]}437 case "adduser-3":438 // OK: returning a new state. But, unnecessary complex and expensive439 return {440 userCount: draft.userCount + 1,441 users: [...draft.users, action.payload]442 }443 case "adduser-4":444 // OK: the immer way445 draft.userCount += 1446 draft.users.push(action.payload)447 return448 }449})450```451452_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._453454## Producing `undefined` using `nothing`455456So, 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`:457458```javascript459produce({}, draft => {460 // don't do anything461})462```463464Versus:465466```javascript467produce({}, draft => {468 // Try to return undefined from the producer469 return undefined470})471```472473The 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.474475However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:476477```javascript478import produce, {nothing} from "immer"479480const state = {481 hello: "world"482}483484produce(state, draft => {})485produce(state, draft => undefined)486// Both return the original state: { hello: "world"}487488produce(state, draft => nothing)489// Produces a new state, 'undefined'490```491492N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.493494## Inline shortcuts using `void`495496Draft 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.497498In 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`.499500```javascript501// Single mutation502produce(draft => void (draft.user.age += 1))503504// Multiple mutations505produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))506```507508Code 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.509510## Extracting the original object from a proxied instance511512Immer 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.513514```js515import {original} from "immer"516517const baseState = {users: [{name: "Richie"}]}518const nextState = produce(baseState, draftState => {519 original(draftState.users) // is === baseState.users520})521```522523Just want to know if a value is a proxied instance? Use the `isDraft` function!524525```js526import {isDraft} from "immer"527528const baseState = {users: [{name: "Bobby"}]}529const nextState = produce(baseState, draft => {530 isDraft(draft) // => true531 isDraft(draft.users) // => true532 isDraft(draft.users[0]) // => true533})534isDraft(nextState) // => false535```536537## Auto freezing538539Immer 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.540541_⚠️ If auto freezing is enabled, recipes are not entirely side-effect free: Any plain object or array that ends up in the produced result, will be frozen, even when these objects were not frozen before the start of the producer! ⚠️_542543## Immer on older JavaScript environments?544545By 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.546547## Importing immer548549`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:550551```javascript552import produce from "immer"553import {produce} from "immer"554555const {produce} = require("immer")556const produce = require("immer").produce557const produce = require("immer").default558559import unleashTheMagic from "immer"560import {produce as unleashTheMagic} from "immer"561```562563## Supported object types564565Plain objects and arrays are always drafted by Immer.566567Every 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.568569```js570import {immerable} from "immer"571572class Foo {573 [immerable] = true // Option 1574575 constructor() {576 this[immerable] = true // Option 2577 }578}579580Foo[immerable] = true // Option 3581```582583For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.584585When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.586587Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:588589```js590const state = {591 set: new Set(),592 map: new Map()593}594const nextState = produce(state, draft => {595 // Don't use any Set methods, as that mutates the instance!596 draft.set.add("foo") // ❌597598 // 1. Instead, clone the set (just once)599 const newSet = new Set(draft.set) // ✅600601 // 2. Mutate the clone (just in this producer)602 newSet.add("foo")603604 // 3. Update the draft with the new set605 draft.set = newSet606607 // Similarly, don't use any Map methods.608 draft.map.set("foo", "bar") // ❌609610 // 1. Instead, clone the map (just once)611 const newMap = new Map(draft.map) // ✅612613 // 2. Mutate it614 newMap.set("foo", "bar")615616 // 3. Update the draft617 draft.map = newMap618})619```620621## TypeScript or Flow622623The 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.624625The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:626627```ts628import produce from "immer"629630interface State {631 readonly x: number632}633634// `x` cannot be modified here635const state: State = {636 x: 0637}638639const newState = produce(state, draft => {640 // `x` can be modified here641 draft.x++642})643644// `newState.x` cannot be modified here645```646647This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!648649For curried reducers, the type is inferred from the first argument of recipe function, so make sure to type it. The `Draft` utility type can be used if the state argument type is immutable:650651```ts652import produce, {Draft} from "immer"653654interface State {655 readonly x: number656}657658// `x` cannot be modified here659const state: State = {660 x: 0661}662663const increment = produce((draft: Draft<State>, inc: number) => {664 // `x` can be modified here665 draft.x += inc666})667668const newState = increment(state, 2)669// `newState.x` cannot be modified here670```671672**Note:** Immer v1.9+ supports TypeScript v3.1+ only.673674**Note:** Immer v3.0+ supports TypeScript v3.4+ only.675676# Pitfalls6776781. 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).6791. 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.6801. 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.6811. 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)})`6821. 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.683684## Cool things built with immer685686- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_687- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_688- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_689- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_690- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_691- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_692- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_693- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_694- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse React (useReducer()) and Redux reducers with Typescript_695- [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_696- [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_697- [redux-immer](https://github.com/salvoravida/redux-immer) _is used to create an equivalent function of Redux combineReducers that works with `immer` state. Like `redux-immutable` but for `immer`_698- ... and [many more](https://www.npmjs.com/browse/depended/immer)699700## How does Immer work?701702Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).703704## Example patterns.705706_For those who have to go back to thinking in object updates :-)_707708```javascript709import produce from "immer"710711// object mutations712const todosObj = {713 id1: {done: false, body: "Take out the trash"},714 id2: {done: false, body: "Check Email"}715}716717// add718const addedTodosObj = produce(todosObj, draft => {719 draft["id3"] = {done: false, body: "Buy bananas"}720})721722// delete723const deletedTodosObj = produce(todosObj, draft => {724 delete draft["id1"]725})726727// update728const updatedTodosObj = produce(todosObj, draft => {729 draft["id1"].done = true730})731732// array mutations733const todosArray = [734 {id: "id1", done: false, body: "Take out the trash"},735 {id: "id2", done: false, body: "Check Email"}736]737738// add739const addedTodosArray = produce(todosArray, draft => {740 draft.push({id: "id3", done: false, body: "Buy bananas"})741})742743// delete744const deletedTodosArray = produce(todosArray, draft => {745 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)746 // or (slower):747 // return draft.filter(todo => todo.id !== "id1")748})749750// update751const updatedTodosArray = produce(todosArray, draft => {752 draft[draft.findIndex(todo => todo.id === "id1")].done = true753})754```755756## Performance757758Here 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.759760These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.761762![performance.png](images/performance.png)763764Most important observation:765766- 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.767- 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)768- Generating patches doesn't significantly slow immer down769- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.770771## Migration772773**Immer 2.\* -> 3.0**774775In your producers, make sure you're not treating `this` as the draft. (see here: https://github.com/immerjs/immer/issues/308)776777Upgrade to `typescript@^3.4` if you're a TypeScript user.778779**Immer 1.\* -> 2.0**780781Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.782783**Immer 2.1 -> 2.2**784785When using TypeScript, for curried reducers that are typed in the form `produce<Type>((arg) => { })`, rewrite this to `produce((arg: Type) => { })` or `produce((arg: Draft<Type>) => { })` for correct inference.786787## FAQ788789_(for those who skimmed the above instead of actually reading)_790791**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**792793A: Yes794795**Q: Does Immer support deep updates?**796797A: Yes798799**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**800801A: Yes802803**Q: Can I typecheck my data structures when using Immer?**804805A: Yes806807**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**808809A: Yes810811**Q: Is it fast?**812813A: Yes814815**Q: Idea! Can Immer freeze the state for me?**816817A: Yes818819## Credits820821Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.822823## Donations824825A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)
deleted:docs/doc2.md-7 removed
deleted:docs/doc3.md-14 removed
deleted:docs/exampledoc4.md-6 removed
deleted:docs/exampledoc5.md-6 removed
modified:website/i18n/en.json+2 added-15 removed
modified:website/siteConfig.js+11 added-31 removed
modified:readme.md-820 removed
11 unmodified lines
1213Did 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>1415---1617- 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>`2223---2425- 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)2728Immer (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.2930The basic idea is that you will apply all your changes to a temporary _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.3132![immer-hd.png](images/hd/immer.png)3334Using 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).3536A 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.3738## External resources3940- 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 Weststrate45- [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/)4647## 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## Benefits9697- 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.103- Small [![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)104105Read 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## Currying183184Passing 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.185186For 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```214215Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).216217If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:218219```javascript220import produce from "immer"221222const byId = produce(223 (draft, action) => {224 switch (action.type) {225 case RECEIVE_PRODUCTS:226 action.products.forEach(product => {227 draft[product.id] = product228 })229 return230 }231 },232 {233 1: {id: 1, name: "product-1"}234 }235)236```237238##### Fun with currying239240A 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:241242```javascript243import produce from "immer"244const spread = produce(Object.assign)245246const base = {x: 1, y: 1}247248console.log({...base, y: 1} === base) // false249console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced250console.log(spread(base, {y: 2}) === base) // false, produced a new object as it should251```252253## Patches254255During 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.256257Patches are useful in few scenarios:258259- To exchange incremental updates with other parties, for example over websockets260- For debugging / traces, to see precisely how state is changed over time261- As basis for undo/redo or as an approach to replay changes on a slightly different state tree262263To 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:264265```javascript266import produce, {applyPatches} from "immer"267268let state = {269 name: "Micheal",270 age: 32271}272273// Let's assume the user is in a wizard, and we don't know whether274// his changes should end up in the base state ultimately or not...275let fork = state276// all the changes the user made in the wizard277let changes = []278// the inverse of all the changes made in the wizard279let inverseChanges = []280281fork = produce(282 fork,283 draft => {284 draft.age = 33285 },286 // The third argument to produce is a callback to which the patches will be fed287 (patches, inversePatches) => {288 changes.push(...patches)289 inverseChanges.push(...inversePatches)290 }291)292293// In the meantime, our original state is replaced, as, for example,294// some changes were received from the server295state = produce(state, draft => {296 draft.name = "Michel"297})298299// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!300state = applyPatches(state, changes)301302// state now contains the changes from both code paths!303expect(state).toEqual({304 name: "Michel", // changed by the server305 age: 33 // changed by the wizard306})307308// Finally, even after finishing the wizard, the user might change his mind and undo his changes...309state = applyPatches(state, inverseChanges)310expect(state).toEqual({311 name: "Michel", // Not reverted312 age: 32 // Reverted313})314```315316The 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:317318```json319[320 {321 "op": "replace",322 "path": ["profile"],323 "value": {"name": "Veria", "age": 5}324 },325 {"op": "remove", "path": ["tags", 3]}326]327```328329```json330[331 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},332 {"op": "add", "path": ["tags", 3], "value": "kiddo"}333]334```335336### `produceWithPatches`337338Instead of setting up a patch listener, an easier way to obtain the patches is to use `produceWithPatches`, which has the same signature as `produce`, except that it doesn't return just the next state, but a tuple consisting of `[nextState, patches, inversePatches]`. Like `produce`, `produceWithPatches` supports currying as well.339340```javascript341import {produceWithPatches} from "immer"342343const [nextState, patches, inversePatches] = produceWithPatches(344 {345 age: 33346 },347 draft => {348 draft.age++349 }350)351```352353Which produces:354355```javascript356;[357 {358 age: 34359 },360 [361 {362 op: "replace",363 path: ["age"],364 value: 34365 }366 ],367 [368 {369 op: "replace",370 path: ["age"],371 value: 33372 }373 ]374]375```376377For 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)378379Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.380381## Async producers382383It 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:384385```javascript386import produce from "immer"387388const user = {389 name: "michel",390 todos: []391}392393const loadedUser = await produce(user, async function(draft) {394 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()395})396```397398_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._399400## `createDraft` and `finishDraft`401402`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:403404```javascript405import {createDraft, finishDraft} from "immer"406407const user = {408 name: "michel",409 todos: []410}411412const draft = createDraft(user)413draft.todos = await (await window.fetch("http://host/" + draft.name)).json()414const loadedUser = finishDraft(draft)415```416417Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.418419_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._420421## Returning data from producers422423It 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`.424425It 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:426427```javascript428const userReducer = produce((draft, action) => {429 switch (action.type) {430 case "renameUser":431 // OK: we modify the current state432 draft.users[action.payload.id].name = action.payload.name433 return draft // same as just 'return'434 case "loadUsers":435 // OK: we return an entirely new state436 return action.payload437 case "adduser-1":438 // NOT OK: This doesn't do change the draft nor return a new state!439 // It doesn't modify the draft (it just redeclares it)440 // In fact, this just doesn't do anything at all441 draft = {users: [...draft.users, action.payload]}442 return443 case "adduser-2":444 // NOT OK: modifying draft *and* returning a new state445 draft.userCount += 1446 return {users: [...draft.users, action.payload]}447 case "adduser-3":448 // OK: returning a new state. But, unnecessary complex and expensive449 return {450 userCount: draft.userCount + 1,451 users: [...draft.users, action.payload]452 }453 case "adduser-4":454 // OK: the immer way455 draft.userCount += 1456 draft.users.push(action.payload)457 return458 }459})460```461462_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._463464## Producing `undefined` using `nothing`465466So, 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`:467468```javascript469produce({}, draft => {470 // don't do anything471})472```473474Versus:475476```javascript477produce({}, draft => {478 // Try to return undefined from the producer479 return undefined480})481```482483The 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.484485However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:486487```javascript488import produce, {nothing} from "immer"489490const state = {491 hello: "world"492}493494produce(state, draft => {})495produce(state, draft => undefined)496// Both return the original state: { hello: "world"}497498produce(state, draft => nothing)499// Produces a new state, 'undefined'500```501502N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.503504## Inline shortcuts using `void`505506Draft 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.507508In 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`.509510```javascript511// Single mutation512produce(draft => void (draft.user.age += 1))513514// Multiple mutations515produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))516```517518Code 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.519520## Extracting the original object from a proxied instance521522Immer 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.523524```js525import {original} from "immer"526527const baseState = {users: [{name: "Richie"}]}528const nextState = produce(baseState, draftState => {529 original(draftState.users) // is === baseState.users530})531```532533Just want to know if a value is a proxied instance? Use the `isDraft` function!534535```js536import {isDraft} from "immer"537538const baseState = {users: [{name: "Bobby"}]}539const nextState = produce(baseState, draft => {540 isDraft(draft) // => true541 isDraft(draft.users) // => true542 isDraft(draft.users[0]) // => true543})544isDraft(nextState) // => false545```546547## Auto freezing548549Immer 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.550551_⚠️ If auto freezing is enabled, recipes are not entirely side-effect free: Any plain object or array that ends up in the produced result, will be frozen, even when these objects were not frozen before the start of the producer! ⚠️_552553## Immer on older JavaScript environments?554555By 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.556557## Importing immer558559`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:560561```javascript562import produce from "immer"563import {produce} from "immer"564565const {produce} = require("immer")566const produce = require("immer").produce567const produce = require("immer").default568569import unleashTheMagic from "immer"570import {produce as unleashTheMagic} from "immer"571```572573## Supported object types574575Plain objects and arrays are always drafted by Immer.576577Every 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.578579```js580import {immerable} from "immer"581582class Foo {583 [immerable] = true // Option 1584585 constructor() {586 this[immerable] = true // Option 2587 }588}589590Foo[immerable] = true // Option 3591```592593For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.594595When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.596597Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:598599```js600const state = {601 set: new Set(),602 map: new Map()603}604const nextState = produce(state, draft => {605 // Don't use any Set methods, as that mutates the instance!606 draft.set.add("foo") // ❌607608 // 1. Instead, clone the set (just once)609 const newSet = new Set(draft.set) // ✅610611 // 2. Mutate the clone (just in this producer)612 newSet.add("foo")613614 // 3. Update the draft with the new set615 draft.set = newSet616617 // Similarly, don't use any Map methods.618 draft.map.set("foo", "bar") // ❌619620 // 1. Instead, clone the map (just once)621 const newMap = new Map(draft.map) // ✅622623 // 2. Mutate it624 newMap.set("foo", "bar")625626 // 3. Update the draft627 draft.map = newMap628})629```630631## TypeScript or Flow632633The 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.634635The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:636637```ts638import produce from "immer"639640interface State {641 readonly x: number642}643644// `x` cannot be modified here645const state: State = {646 x: 0647}648649const newState = produce(state, draft => {650 // `x` can be modified here651 draft.x++652})653654// `newState.x` cannot be modified here655```656657This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!658659For curried reducers, the type is inferred from the first argument of recipe function, so make sure to type it. The `Draft` utility type can be used if the state argument type is immutable:660661```ts662import produce, {Draft} from "immer"663664interface State {665 readonly x: number666}667668// `x` cannot be modified here669const state: State = {670 x: 0671}672673const increment = produce((draft: Draft<State>, inc: number) => {674 // `x` can be modified here675 draft.x += inc676})677678const newState = increment(state, 2)679// `newState.x` cannot be modified here680```681682**Note:** Immer v1.9+ supports TypeScript v3.1+ only.683684**Note:** Immer v3.0+ supports TypeScript v3.4+ only.685686# Pitfalls6876881. 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).6891. 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.6901. 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.6911. 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)})`6921. 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.693694## Cool things built with immer695696- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_697- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_698- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_699- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_700- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_701- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_702- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_703- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_704- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse React (useReducer()) and Redux reducers with Typescript_705- [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_706- [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_707- [redux-immer](https://github.com/salvoravida/redux-immer) _is used to create an equivalent function of Redux combineReducers that works with `immer` state. Like `redux-immutable` but for `immer`_708- ... and [many more](https://www.npmjs.com/browse/depended/immer)709710## How does Immer work?711712Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).713714## Example patterns.715716_For those who have to go back to thinking in object updates :-)_717718```javascript719import produce from "immer"720721// object mutations722const todosObj = {723 id1: {done: false, body: "Take out the trash"},724 id2: {done: false, body: "Check Email"}725}726727// add728const addedTodosObj = produce(todosObj, draft => {729 draft["id3"] = {done: false, body: "Buy bananas"}730})731732// delete733const deletedTodosObj = produce(todosObj, draft => {734 delete draft["id1"]735})736737// update738const updatedTodosObj = produce(todosObj, draft => {739 draft["id1"].done = true740})741742// array mutations743const todosArray = [744 {id: "id1", done: false, body: "Take out the trash"},745 {id: "id2", done: false, body: "Check Email"}746]747748// add749const addedTodosArray = produce(todosArray, draft => {750 draft.push({id: "id3", done: false, body: "Buy bananas"})751})752753// delete754const deletedTodosArray = produce(todosArray, draft => {755 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)756 // or (slower):757 // return draft.filter(todo => todo.id !== "id1")758})759760// update761const updatedTodosArray = produce(todosArray, draft => {762 draft[draft.findIndex(todo => todo.id === "id1")].done = true763})764```765766## Performance767768Here 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.769770These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.771772![performance.png](images/performance.png)773774Most important observation:775776- 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.777- 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)778- Generating patches doesn't significantly slow immer down779- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.780781## Migration782783**Immer 2.\* -> 3.0**784785In your producers, make sure you're not treating `this` as the draft. (see here: https://github.com/immerjs/immer/issues/308)786787Upgrade to `typescript@^3.4` if you're a TypeScript user.788789**Immer 1.\* -> 2.0**790791Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.792793**Immer 2.1 -> 2.2**794795When using TypeScript, for curried reducers that are typed in the form `produce<Type>((arg) => { })`, rewrite this to `produce((arg: Type) => { })` or `produce((arg: Draft<Type>) => { })` for correct inference.796797## FAQ798799_(for those who skimmed the above instead of actually reading)_800801**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**802803A: Yes804805**Q: Does Immer support deep updates?**806807A: Yes808809**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**810811A: Yes812813**Q: Can I typecheck my data structures when using Immer?**814815A: Yes816817**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**818819A: Yes820821**Q: Is it fast?**822823A: Yes824825**Q: Idea! Can Immer freeze the state for me?**826827A: Yes828829## Credits830831Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.832833## Donations834835A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)