doc1.md
This file
Path
docs/doc1.md
825 lines · 29.9 KiB · Markdown
Last changed by
WIPMichel Weststratebefore adoption79ec197
History of this fileTake it
docusuarus initMichel Weststratebefore adoptionb1e2217
lines 1–6why, one step back1---2id: doc13title: Latin-ish4sidebar_label: Example Page5---6WIPMichel Weststratebefore adoption79ec197
lines 7–11why, one step back7- 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>`docusuarus initMichel Weststratebefore adoptionb1e2217
line 12why, one step back12WIPMichel Weststratebefore adoption79ec197
line 13why, one step back13---docusuarus initMichel Weststratebefore adoptionb1e2217
line 14why, one step back14WIPMichel Weststratebefore adoption79ec197
lines 15–16why, one step back15- 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)docusuarus initMichel Weststratebefore adoptionb1e2217
line 17why, one step back17WIPMichel Weststratebefore adoption79ec197
line 18why, one step back18Immer (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.docusuarus initMichel Weststratebefore adoptionb1e2217
line 19why, one step back19WIPMichel Weststratebefore adoption79ec197
lines 20–64why, one step back20The 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.21222324Using 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})docusuarus initMichel Weststratebefore adoptionb1e2217
line 65why, one step back65```WIPMichel Weststratebefore adoption79ec197
lines 66–82why, one step back6667The 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])docusuarus initMichel Weststratebefore adoptionb1e2217
lines 83–84why, one step back83```84WIPMichel Weststratebefore adoption79ec197
line 85why, one step back85## Benefitsdocusuarus initMichel Weststratebefore adoptionb1e2217
line 86why, one step back86WIPMichel Weststratebefore adoption79ec197
lines 87–93why, one step back87- 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 [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)docusuarus initMichel Weststratebefore adoptionb1e2217
line 94why, one step back94WIPMichel Weststratebefore adoption79ec197
line 95why, one step back95Read further to see all these benefits explained.docusuarus initMichel Weststratebefore adoptionb1e2217
line 96why, one step back96WIPMichel Weststratebefore adoption79ec197
line 97why, one step back97## Reducer Exampledocusuarus initMichel Weststratebefore adoptionb1e2217
line 98why, one step back98WIPMichel Weststratebefore adoption79ec197
line 99why, one step back99Here is a simple example of the difference that Immer could make in practice.docusuarus initMichel Weststratebefore adoptionb1e2217
line 100why, one step back100WIPMichel Weststratebefore adoption79ec197
lines 101–825why, one step back101```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.761762763764Most 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 :)