docs: Extended / updated documenation (#824)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Initial improvements, modernized react, add sandboxes * touch
authored by Michel Weststrate · committed by GitHub · parent 7f41483 · Browse files · 8 files·+315 added−170 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+315 added−170 removed
- other:+315 added−170 removed
Provenance
- Commit
847492c- Tree
abbbb89- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
7f41483
8 files changed+315 added−170 removed
modified:.vscode/settings.json+2 added-1 removed
1234456{ "javascript.validate.enable": false, "typescript.tsdk": "node_modules/typescript/lib", "jest.enableInlineErrorMessages": true "jest.enableInlineErrorMessages": true, "cSpell.enabled": true}modified:website/docs/curried-produce.mdx+36 added-41 removed
7 unmodified lines8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12-</center> <details>12+</center>13+<details>14 <summary className="egghead-summary">15 egghead.io lesson 6: Simplify code by using curried _reduce_16 </summary>17 <br />12 unmodified lines30 Hosted on egghead.io31 </a>32 </details>33 33-Passing 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.34+Passing a function as the first argument to `produce` creates a function that doesn't apply `produce` yet to a specific state, but rather creates a function that will apply `produce` to any state that is passed to it in the future. This generally is called _currying_. Take for example the following example:35 35-For example:36-36 ```javascript38-// mapper will be of signature (state, index) => state39-const mapper = produce((draft, index) => {40- draft.index = index41-})37+import produce from "immer"38 43-// example usage44-console.dir([{}, {}, {}].map(mapper))45-//[{index: 0}, {index: 1}, {index: 2}])39+function toggleTodo(state, id) {40+ return produce(state, draft => {41+ const todo = draft.find(todo => todo.id === id)42+ todo.done = !todo.done43+ })44+}45+46+const baseState = [47+ {48+ id: "JavaScript",49+ title: "Learn TypeScript",50+ done: true51+ },52+ {53+ id: "Immer",54+ title: "Try Immer",55+ done: false56+ }57+]58+59+const nextState = toggleTodo(baseState, "Immer")60 ```61 48-This mechanism can also nicely be leveraged to further simplify our example reducer:62+The above pattern of `toggleTodo` is quite typical; pass an existing state to `produce`, modify the `draft`, and then return the result. Since `state` isn't used for anything else than passing it on to `produce`, the above example can be simplified by using the _curried_ form of `produce`, where you pass `produce` only the recipe function, and `produce` will return a new function that will apply recipe to the base state. This allows us to shorten the above `toggleTodo` definition.63 64 ```javascript65 import produce from "immer"66 53-const byId = produce((draft, action) => {54- switch (action.type) {55- case RECEIVE_PRODUCTS:56- action.products.forEach(product => {57- draft[product.id] = product58- })59- return60- }67+// curried producer:68+const toggleTodo = produce((draft, id) => {69+ const todo = draft.find(todo => todo.id === id)70+ todo.done = !todo.done71 })62-```72 64-Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).73+const baseState = [74+ /* as is */75+]76 66-If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:67-68-```javascript69-import produce from "immer"70-71-const byId = produce(72- (draft, action) => {73- switch (action.type) {74- case RECEIVE_PRODUCTS:75- action.products.forEach(product => {76- draft[product.id] = product77- })78- return79- }80- },81- {82- 1: {id: 1, name: "product-1"}83- }84-)77+const nextState = toggleTodo(baseState, "Immer")78 ```79+80+Note that the `id` param has now become part of the recipe function! This pattern of having curried producers combines really neatly with for example the `useState` hook from React, as we will see on the next page.deleted:website/docs/example-reducer.mdx-79 removed
1----2-id: example-reducer3-title: Example Reducer4----5-6-<center>7- <div8- data-ea-publisher="immerjs"9- data-ea-type="image"10- className="horizontal bordered"11- ></div>12-</center>13-<details>14- <summary className="egghead-summary">15- egghead.io lesson 13: Using Immer in a (React) reducer16- </summary>17- <br />18- <div>19- <iframe20- width="760"21- height="427"22- scrolling="no"23- src="https://egghead.io/lessons/react-update-immutable-state-with-react-usereducer-through-immer/embed"24- ></iframe>25- </div>26- <a27- className="egghead-link"28- href="https://egghead.io/lessons/react-update-immutable-state-with-react-usereducer-through-immer"29- >30- Hosted on egghead.io31- </a>32-</details>33-34-Here is a simple example of the difference that Immer could make in practice.35-36-```javascript37-// Reducer with initial state38-const INITIAL_STATE = {}39-// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js40-const byId = (state = INITIAL_STATE, action) => {41- switch (action.type) {42- case RECEIVE_PRODUCTS:43- return {44- ...state,45- ...action.products.reduce((obj, product) => {46- obj[product.id] = product47- return obj48- }, {})49- }50- default:51- return state52- }53-}54-```55-56-After using Immer, our reducer can be expressed as:57-58-```javascript59-import produce from "immer"60-61-// Reducer with initial state62-const INITIAL_STATE = {}63-64-const byId = produce((draft, action) => {65- switch (action.type) {66- case RECEIVE_PRODUCTS:67- action.products.forEach(product => {68- draft[product.id] = product69- })70- break71- }72-}, INITIAL_STATE)73-```74-75-Notice that it is not necessary to handle the default case, a producer that doesn't do anything will return the original state.76-77-Creating 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).78-79-_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 said draft. Don't do that. It removes the benefit of using Redux as a system where each reducer is testable as a pure function. Immer is best used when applied to small, individual pieces of logic._modified:website/docs/example-setstate.mdx+202 added-22 removed
1 ---2 id: example-setstate3-title: React setState example3+title: React & Immer4 ---5 6 <center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12-</center> <details>12+</center>13+<details>14 <summary className="egghead-summary">15 egghead.io lesson 8: Using Immer with _useState_. Or: _useImmer_16 </summary>17 <br />12 unmodified lines30 Hosted on egghead.io31 </a>32 </details>33 33-Deep 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)):34+## useState + Immer35 36+The `useState` hook assumes any state that is stored inside it is treated as immutable. Deep updates in the state of React components can be greatly simplified as by using Immer. To following example shows how to use `produce` in combination with `useState`, and can be tried on [CodeSandbox](https://codesandbox.io/s/immer-usestate-ujkgg?file=/src/index.js).37+38 ```javascript36-/**37- * Classic React.setState with a deep merge38- */39-onBirthDayClick1 = () => {40- this.setState(prevState => ({41- user: {42- ...prevState.user,43- age: prevState.user.age + 144- }45- }))39+import React, { useCallback, useState } from "react";40+import produce from "immer";41+42+const TodoList = () => {43+ const [todos, setTodos] = useState([44+ {45+ id: "React",46+ title: "Learn React",47+ done: true48+ },49+ {50+ id: "Immer",51+ title: "Try Immer",52+ done: false53+ }54+ ]);55+56+ const handleToggle = useCallback((id) => {57+ setTodos(58+ produce((draft) => {59+ const todo = draft.find((todo) => todo.id === id);60+ todo.done = !todo.done;61+ })62+ );63+ }, []);64+65+ const handleAdd = useCallback(() => {66+ setTodos(67+ produce((draft) => {68+ draft.push({69+ id: "todo_" + Math.random(),70+ title: "A new todo",71+ done: false72+ });73+ })74+ );75+ }, []);76+77+ return (<div>{*/ See CodeSandbox */}</div>)78 }79+```80 48-/**49- * ...But, since setState accepts functions,50- * we can just create a curried producer and further simplify!51- */52-onBirthDayClick2 = () => {53- this.setState(54- produce(draft => {55- draft.user.age += 156- })81+## useImmer82+83+Since all state updaters follow the same pattern where the update function is wrapped in `produce`, it is also possible to simply the above by leveraging the [use-immer](https://www.npmjs.com/package/use-immer) package that will wrap updater functions in `produce` automatically:84+85+```javascript86+import React, { useCallback } from "react";87+import { useImmer } from "use-immer";88+89+const TodoList = () => {90+ const [todos, setTodos] = useImmer([91+ {92+ id: "React",93+ title: "Learn React",94+ done: true95+ },96+ {97+ id: "Immer",98+ title: "Try Immer",99+ done: false100+ }101+ ]);102+103+ const handleToggle = useCallback((id) => {104+ setTodos((draft) => {105+ const todo = draft.find((todo) => todo.id === id);106+ todo.done = !todo.done;107+ });108+ }, []);109+110+ const handleAdd = useCallback(() => {111+ setTodos((draft) => {112+ draft.push({113+ id: "todo_" + Math.random(),114+ title: "A new todo",115+ done: false116+ });117+ });118+ }, []);119+120+ // etc121+```122+123+For the full demo see [CodeSandbox](https://codesandbox.io/s/use-immer-bvd5v?file=/src/index.js).124+125+## useReducer + Immer126+127+Similarly to `useState`, `useReducer` combines neatly with Immer as well, as demonstrated in this [CodeSandbox](https://codesandbox.io/s/immer-usereducer-bqpzn?file=/src/index.js:0-1018):128+129+```javascript130+import React, {useCallback, useReducer} from "react"131+import produce from "immer"132+133+const TodoList = () => {134+ const [todos, dispatch] = useReducer(135+ produce((draft, action) => {136+ switch (action.type) {137+ case "toggle":138+ const todo = draft.find(todo => todo.id === action.id)139+ todo.done = !todo.done140+ break141+ case "add":142+ draft.push({143+ id: "todo_" + Math.random(),144+ title: "A new todo",145+ done: false146+ })147+ break148+ default:149+ break150+ }151+ }),152+ [153+ /* initial todos */154+ ]155 )156+157+ const handleToggle = useCallback(id => {158+ dispatch({159+ type: "toggle",160+ id161+ })162+ }, [])163+164+ const handleAdd = useCallback(() => {165+ dispatch({166+ type: "add"167+ })168+ }, [])169+170+ // etc171 }172 ```173+174+## useImmerReducer175+176+...which again, can be slightly shorted by `useImmerReducer` from the `use-immer` package ([demo](https://codesandbox.io/s/useimmerreducer-sycpb?file=/src/index.js)):177+178+```javascript179+import React, { useCallback } from "react";180+import { useImmerReducer } from "use-immer";181+182+const TodoList = () => {183+ const [todos, dispatch] = useImmerReducer(184+ (draft, action) => {185+ switch (action.type) {186+ case "toggle":187+ const todo = draft.find((todo) => todo.id === action.id);188+ todo.done = !todo.done;189+ break;190+ case "add":191+ draft.push({192+ id: "todo_" + Math.random(),193+ title: "A new todo",194+ done: false195+ });196+ break;197+ default:198+ break;199+ }200+ },201+ [ /* initial todos */ ]202+ );203+204+ //etc205+206+```207+208+## Redux + Immer209+210+Redux + Immer is extensively covered in the documentation of [Redux Toolkit](https://redux-toolkit.js.org/usage/immer-reducers). For Redux without Redux Toolkit, the same trick as applied to `useReducer` above can be applied: wrap the reducer function with `produce`, and you can safely mutate the draft!211+212+For example:213+214+```javascript215+import produce from "immer"216+217+// Reducer with initial state218+const INITIAL_STATE = [219+ /* bunch of todos */220+]221+222+const todosReducer = produce((draft, action) => {223+ switch (action.type) {224+ case "toggle":225+ const todo = draft.find(todo => todo.id === action.id)226+ todo.done = !todo.done227+ break228+ case "add":229+ draft.push({230+ id: "todo_" + Math.random(),231+ title: "A new todo",232+ done: false233+ })234+ break235+ default:236+ break237+ }238+})239+```modified:website/docs/introduction.md+52 added-15 removed
19 unmodified lines202122232424252626272828293030313232333435343536373839403941424344434546474849504849505152535455565758596061626364656667686970717273747576777879808182548384858687888990919293949596609798991001011026610310419 unmodified lines- Free in-depth Egghead.io course: [Immutable JavaScript Data Structures with Immer (58m)](https://egghead.io/courses/immutable-javascript-data-structures-with-immer)
---
Immer (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.Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.
The 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.### Immer simplifies handling immutable data structures
Immer can be used in any context in which immutable data structures need to be used. For example in combination with React state, React or Redux reducers, or configuration management. Immutable data structures allow for (efficient) change detection: if the reference to an object didn't change, the object itself did not change. In addition, it makes cloning relatively cheap: Unchanged parts of a data tree don't need to be copied and are shared in memory with older versions of the same state.
Using Immer is like having a personal assistant. The assistant 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).Generally speaking, these benefits can be achieved by making sure you never change any property of an object, array or map, but by always creating an altered copy instead. In practice this can result in code that is quite cumbersome to write, and it is easy to accidentally violate those constraints. Immer will help you to follow the immutable data paradigm by addressing these pain points:
## Quick Example1. Immer will detect accidental mutations and throw an error.2. Immer will remove the need for the typical boilerplate code that is needed when creating deep updates to immutable objects: Without Immer, object copies need to be made by hand at every level. Typically by using a lot of `...` spread operations. When using Immer, changes are made to a `draft` object, that records the changes and takes care of creating the necessary copies, without ever affecting the original object.3. When using Immer, you don't need to learn dedicated APIs or data structures to benefit from the paradigm. With Immer you'll use plain JavaScript data structures, and use the well know mutable JavaScript APIs, but safely.
```javascriptimport produce from "immer"### A quick example for comparison
```javascriptconst baseState = [ { todo: "Learn typescript", title: "Learn TypeScript", done: true }, { todo: "Try immer", title: "Try Immer", done: false }]```
const nextState = produce(baseState, draftState => { draftState.push({todo: "Tweet about it"}) draftState[1].done = trueImagine we have the above base state, and we'll need to update the second todo, and add a third one. However, we don't want to mutate the original `baseState`, and we want to avoid deep cloning as well (to preserve the first todo).
#### Without Immer
Without Immer, we'll have to carefully shallow copy every level of the state structure that is affected by our change:
```javascriptconst nextState = baseState.slice() // shallow clone the arraynextState[1] = { // replace element 1... ...nextState[1], // with a shallow clone of element 1 done: true // ...combined with the desired update}// since nextState was freshly cloned, using push is safe here,// but doing the same thing at any arbitrary time in the future would// violate the immutability principles and introduce a bug!nextState.push({title: "Tweet about it"})```
#### With Immer
With Immer, this process is more straightforward. We can leverage the `produce` function, which takes as first argument the state we want to start from, and as second argument we pass a function, called the _recipe_, that is passed a `draft` to which we can apply straightforward mutations. Those mutations are recorded and used to produce the next state once the recipe is done. `produce` will take care of all the necessary copying, and protect against future accidental modifications as well by freezing the data.
```javascriptimport produce from "immer"
const nextState = produce(baseState, draft => { draft[1].done = true draft.push({title: "Tweet about it"})})```
The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will be a new immutable tree that reflects all changes made to `draftState` (and structurally sharing the things that weren't changed).Looking for Immer in combination with React? Feel free to skip ahead to the [React + Immer](example-setstate) page.
### How Immer works
The basic idea is that with Immer you will apply all your changes to a temporary _draft_, 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.

Using Immer is like having a personal assistant. The assistant 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).
Head to the [next section](./produce.mdx) to further dive into `produce`.
## Benefits
- Immutability with normal JavaScript objects, arrays, Sets and Maps. No new APIs to learn!- Follow the immutable data paradigm, while using normal JavaScript objects, arrays, Sets and Maps. No new APIs or "mutation patterns" to learn!- Strongly typed, no string based paths selectors etc.- Structural sharing out of the box- Object freezing out of the box- Deep updates are a breeze- Boilerplate reduction. Less noise, more concise code.- First class support for patches- First class support for JSON patches- Small: 3KB gzippedmodified:website/docs/produce.mdx+22 added-10 removed
7 unmodified lines8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12-</center>13-<details>12+</center> <details>13 <summary className="egghead-summary">14 egghead.io lesson 3: Simplifying deep updates with _produce_15 </summary>16 <br />14 unmodified lines31 </details>32 33 The Immer package exposes a default function that does all the work.34 36-`produce(currentState, producer: (draftState) => void): nextState`35+`produce(currentState, recipe: (draftState) => void): nextState`36 38-There is also a curried overload that is explained [in a later section](./curried-produce.mdx).37+`produce` takes a base state, and a _recipe_ that can be used perform all the desired mutations on the `draft` that is passed in. The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.38 39+Inside the recipe, all standard JavaScript APIs can be used on the `draft` object, including field assignments, `delete` operations, and mutating array, Map and Set operations like `push`, `pop`, `splice`, `set`, `sort`, `remove`, etc.40+41+Any of those mutations don't have to happen at the root, but it is allowed to modify anything anywhere deep inside the draft: `draft.todos[0].tags["urgent"].author.age = 56`42+43+Note that the recipe function itself normally doesn't return anything. However, it is possible to return in case you want to replace the `draft` object in it's entirety with another object, for more details see [returning new data](return).44+45 ## Example46 47 ```javascript48 import produce from "immer"49 50 const baseState = [51 {47- todo: "Learn typescript",52+ title: "Learn TypeScript",53 done: true54 },55 {51- todo: "Try immer",56+ title: "Try Immer",57 done: false58 }59 ]60 61 const nextState = produce(baseState, draftState => {57- draftState.push({todo: "Tweet about it"})62+ draftState.push({title: "Tweet about it"})63 draftState[1].done = true64 })65 ```66 62-The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.63-67 ```javascript68 // the new item is only added to the next state,69 // base state is unmodified70 expect(baseState.length).toBe(2)4 unmodified lines75 expect(nextState[1].done).toBe(true)76 77 // unchanged data is structurally shared78 expect(nextState[0]).toBe(baseState[0])76-// changed data not (dûh)79+// ...but changed data isn't.80 expect(nextState[1]).not.toBe(baseState[1])81 ```82+83+### Terminology84+85+- `(base)state`, the immutable state passed to `produce`86+- `recipe`: the second argument of `produce`, that captures how the base state should be "mutated".87+- `draft`: the first argument of any `recipe`, which is a proxy to the original base state that can be safely mutated.88+- `producer`. A function that uses `produce` and is generally of the form `(baseState, ...arguments) => resultState`89+90+Note that it isn't strictly necessary to name the first argument of the recipe `draft`. You can name it anything you want, for example `users`. Using `draft` as a name is just a convention to signal: "mutation is OK here".modified:website/docusaurus.config.js+1 added-1 removed
11234574 unmodified lines// See https://v2.docusaurus.io/docs/configuration for more information// See https://v2.docusaurus.io/docs/configuration for more information.
module.exports = { title: "Immer", tagline: "Create the next immutable state by mutating the current one.",74 unmodified linesmodified:website/sidebars.js-1 removed
3 unmodified lines4 "introduction",5 "installation",6 "produce",7 "curried-produce",8- "example-reducer",8 "example-setstate",9 "update-patterns"10 ],11 "Advanced Features": [21 unmodified lines