Skip to content
Myr

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

8 files+315 added−170 removed

modified:.vscode/settings.json+2 added-1 removed
modified:website/docs/curried-produce.mdx+36 added-41 removed
7 unmodified lines
8 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 lines
30 Hosted on egghead.io31 </a>32</details>3333Passing 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.34Passing 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:3535For example:3636```javascript38// mapper will be of signature (state, index) => state39const mapper = produce((draft, index) => {40 draft.index = index41})37import produce from "immer"3843// example usage44console.dir([{}, {}, {}].map(mapper))45//[{index: 0}, {index: 1}, {index: 2}])39function toggleTodo(state, id) {40 return produce(state, draft => {41 const todo = draft.find(todo => todo.id === id)42 todo.done = !todo.done43 })44}4546const baseState = [47 {48 id: "JavaScript",49 title: "Learn TypeScript",50 done: true51 },52 {53 id: "Immer",54 title: "Try Immer",55 done: false56 }57]5859const nextState = toggleTodo(baseState, "Immer")60```6148This mechanism can also nicely be leveraged to further simplify our example reducer:62The 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.6364```javascript65import produce from "immer"6653const 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:68const toggleTodo = produce((draft, id) => {69 const todo = draft.find(todo => todo.id === id)70 todo.done = !todo.done71})62```7264Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).73const baseState = [74 /* as is */75]7666If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:6768```javascript69import produce from "immer"7071const 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)77const nextState = toggleTodo(baseState, "Immer")78```7980Note 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---2id: example-reducer3title: Example Reducer4---56<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>3334Here is a simple example of the difference that Immer could make in practice.3536```javascript37// Reducer with initial state38const INITIAL_STATE = {}39// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js40const 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```5556After using Immer, our reducer can be expressed as:5758```javascript59import produce from "immer"6061// Reducer with initial state62const INITIAL_STATE = {}6364const 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```7475Notice that it is not necessary to handle the default case, a producer that doesn't do anything will return the original state.7677Creating 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).7879_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---2id: example-setstate3title: React setState example3title: React & Immer4---56<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 lines
30 Hosted on egghead.io31 </a>32</details>3333Deep 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 + Immer3536The `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).3738```javascript36/**37 * Classic React.setState with a deep merge38 */39onBirthDayClick1 = () => {40 this.setState(prevState => ({41 user: {42 ...prevState.user,43 age: prevState.user.age + 144 }45 }))39import React, { useCallback, useState } from "react";40import produce from "immer";4142const 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 ]);5556 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 }, []);6465 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 }, []);7677 return (<div>{*/ See CodeSandbox */}</div>)78}79```8048/**49 * ...But, since setState accepts functions,50 * we can just create a curried producer and further simplify!51 */52onBirthDayClick2 = () => {53 this.setState(54 produce(draft => {55 draft.user.age += 156 })81## useImmer8283Since 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:8485```javascript86import React, { useCallback } from "react";87import { useImmer } from "use-immer";8889const 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 ]);102103 const handleToggle = useCallback((id) => {104 setTodos((draft) => {105 const todo = draft.find((todo) => todo.id === id);106 todo.done = !todo.done;107 });108 }, []);109110 const handleAdd = useCallback(() => {111 setTodos((draft) => {112 draft.push({113 id: "todo_" + Math.random(),114 title: "A new todo",115 done: false116 });117 });118 }, []);119120 // etc121```122123For the full demo see [CodeSandbox](https://codesandbox.io/s/use-immer-bvd5v?file=/src/index.js).124125## useReducer + Immer126127Similarly 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):128129```javascript130import React, {useCallback, useReducer} from "react"131import produce from "immer"132133const 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 )156157 const handleToggle = useCallback(id => {158 dispatch({159 type: "toggle",160 id161 })162 }, [])163164 const handleAdd = useCallback(() => {165 dispatch({166 type: "add"167 })168 }, [])169170 // etc171}172```173174## useImmerReducer175176...which again, can be slightly shorted by `useImmerReducer` from the `use-immer` package ([demo](https://codesandbox.io/s/useimmerreducer-sycpb?file=/src/index.js)):177178```javascript179import React, { useCallback } from "react";180import { useImmerReducer } from "use-immer";181182const 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 );203204 //etc205206```207208## Redux + Immer209210Redux + 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!211212For example:213214```javascript215import produce from "immer"216217// Reducer with initial state218const INITIAL_STATE = [219 /* bunch of todos */220]221222const 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
modified:website/docs/produce.mdx+22 added-10 removed
7 unmodified lines
8 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 lines
31</details>3233The Immer package exposes a default function that does all the work.3436`produce(currentState, producer: (draftState) => void): nextState`35`produce(currentState, recipe: (draftState) => void): nextState`3638There 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`.3839Inside 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.4041Any 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`4243Note 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).4445## Example4647```javascript48import produce from "immer"4950const 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]6061const nextState = produce(baseState, draftState => {57 draftState.push({todo: "Tweet about it"})62 draftState.push({title: "Tweet about it"})63 draftState[1].done = true64})65```6662The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.6367```javascript68// the new item is only added to the next state,69// base state is unmodified70expect(baseState.length).toBe(2)
4 unmodified lines
75expect(nextState[1].done).toBe(true)7677// unchanged data is structurally shared78expect(nextState[0]).toBe(baseState[0])76// changed data not (dûh)79// ...but changed data isn't.80expect(nextState[1]).not.toBe(baseState[1])81```8283### Terminology8485- `(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`8990Note 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
modified:website/sidebars.js-1 removed
3 unmodified lines
4 "introduction",5 "installation",6 "produce",7 "curried-produce",8 "example-reducer",8 "example-setstate",9 "update-patterns"10 ],11 "Advanced Features": [
21 unmodified lines