Skip to content
Myr

example-setstate.mdx

This file

Path

website/docs/example-setstate.mdx

257 lines · 5.6 KiB

Last changed by

docs: show todo.done in useImmer checkbox example (#1275)Hashim Khanbefore adoption36f340c

History of this file

Take it

The walk stopped after 200 commits: lines older than 07f5cc9 point at it.

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 1–11why, one step back
1---
2id: example-setstate3title: React & Immer4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

lines 12–13why, one step back
12</center>
13<details>

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 14–38why, one step back
14 <summary className="egghead-summary">
15 egghead.io lesson 8: Using Immer with _useState_. Or: _useImmer_16 </summary>17 <br />18 <div>19 <iframe20 width="760"21 height="427"22 scrolling="no"23 src="https://egghead.io/lessons/react-immutable-update-state-inside-react-components-with-useimmer/embed"24 ></iframe>25 </div>26 <a27 className="egghead-link"28 href="https://egghead.io/lessons/react-immutable-update-state-inside-react-components-with-useimmer"29 >30 Hosted on egghead.io31 </a>32</details>3334## 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. The 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```javascript

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

lines 39–40why, one step back
39import React, {useCallback, useState} from "react"
40import {produce} from "immer"

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 41–42why, one step back
41
42const TodoList = () => {

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

lines 43–54why, one step back
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 ])

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 55why, one step back
55

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

lines 56–63why, one step back
56 const handleToggle = useCallback(id => {
57 setTodos(58 produce(draft => {59 const todo = draft.find(todo => todo.id === id)60 todo.done = !todo.done61 })62 )63 }, [])

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 64why, one step back
64

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

lines 65–75why, one step back
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 }, [])

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

line 76why, one step back
76

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

line 77why, one step back
77 return <div>{/* See CodeSandbox */}</div>

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 78–119why, one step back
78}
79```8081## useImmer8283Since all state updaters follow the same pattern where the update function is wrapped in `produce`, it is also possible to simplify 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 }, []);119

docs: show todo.done in useImmer checkbox example (#1275)Hashim Khanbefore adoption36f340c

lines 120–139why, one step back
120 return (
121 <ul>122 {todos.map((todo) => (123 <li key={todo.id}>124 <label>125 <input126 type="checkbox"127 checked={todo.done}128 onChange={() => handleToggle(todo.id)}129 />130 {todo.title}131 </label>132 </li>133 ))}134 <button type="button" onClick={handleAdd}>135 Add todo136 </button>137 </ul>138 );139};

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 140–147why, one step back
140```
141142## useReducer + Immer143144Similarly 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):145146```javascript147import React, {useCallback, useReducer} from "react"

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 148why, one step back
148import {produce} from "immer"

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 149–232why, one step back
149
150const TodoList = () => {151 const [todos, dispatch] = useReducer(152 produce((draft, action) => {153 switch (action.type) {154 case "toggle":155 const todo = draft.find(todo => todo.id === action.id)156 todo.done = !todo.done157 break158 case "add":159 draft.push({160 id: action.id,161 title: "A new todo",162 done: false163 })164 break165 default:166 break167 }168 }),169 [170 /* initial todos */171 ]172 )173174 const handleToggle = useCallback(id => {175 dispatch({176 type: "toggle",177 id178 })179 }, [])180181 const handleAdd = useCallback(() => {182 dispatch({183 type: "add",184 id: "todo_" + Math.random()185 })186 }, [])187188 // etc189}190```191192## useImmerReducer193194...which again, can be slightly shorted by `useImmerReducer` from the `use-immer` package ([demo](https://codesandbox.io/s/useimmerreducer-sycpb?file=/src/index.js)):195196```javascript197import React, { useCallback } from "react";198import { useImmerReducer } from "use-immer";199200const TodoList = () => {201 const [todos, dispatch] = useImmerReducer(202 (draft, action) => {203 switch (action.type) {204 case "toggle":205 const todo = draft.find((todo) => todo.id === action.id);206 todo.done = !todo.done;207 break;208 case "add":209 draft.push({210 id: action.id,211 title: "A new todo",212 done: false213 });214 break;215 default:216 break;217 }218 },219 [ /* initial todos */ ]220 );221222 //etc223224```225226## Redux + Immer227228Redux + 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!229230For example:231232```javascript

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 233why, one step back
233import {produce} from "immer"

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 234–257why, one step back
234
235// Reducer with initial state236const INITIAL_STATE = [237 /* bunch of todos */238]239240const todosReducer = produce((draft, action) => {241 switch (action.type) {242 case "toggle":243 const todo = draft.find(todo => todo.id === action.id)244 todo.done = !todo.done245 break246 case "add":247 draft.push({248 id: action.id,249 title: "A new todo",250 done: false251 })252 break253 default:254 break255 }256})257```