Skip to content
Myr

example-setstate.mdx

This file

Path

website/docs/example-setstate.mdx

239 lines · 5.4 KiB

Last changed by

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

History of this file

Take it

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

lines 1–2why, one step back
1---
2id: example-setstate

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

line 3why, one step back
3title: React & Immer

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

lines 4–11why, one step back
4---
56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>

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

line 12why, one step back
12</center> <details>

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

lines 13–32why, one step back
13 <summary className="egghead-summary">
14 egghead.io lesson 8: Using Immer with _useState_. Or: _useImmer_15 </summary>16 <br />17 <div>18 <iframe19 width="760"20 height="427"21 scrolling="no"22 src="https://egghead.io/lessons/react-immutable-update-state-inside-react-components-with-useimmer/embed"23 ></iframe>24 </div>25 <a26 className="egghead-link"27 href="https://egghead.io/lessons/react-immutable-update-state-inside-react-components-with-useimmer"28 >29 Hosted on egghead.io30 </a>31</details>32

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

line 33why, one step back
33## useState + Immer

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

line 34why, one step back
34

docs: Update example-setstate.mdx (#829)SyedTayyabUlMazharbefore adoptionbc890f7

line 35why, one step back
35The `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).

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

line 36why, one step back
36

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

line 37why, one step back
37```javascript

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

line 38why, one step back
38import React, { useCallback, useState } from "react";

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

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

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 40–76why, one step back
40
41const TodoList = () => {42 const [todos, setTodos] = useState([43 {44 id: "React",45 title: "Learn React",46 done: true47 },48 {49 id: "Immer",50 title: "Try Immer",51 done: false52 }53 ]);5455 const handleToggle = useCallback((id) => {56 setTodos(57 produce((draft) => {58 const todo = draft.find((todo) => todo.id === id);59 todo.done = !todo.done;60 })61 );62 }, []);6364 const handleAdd = useCallback(() => {65 setTodos(66 produce((draft) => {67 draft.push({68 id: "todo_" + Math.random(),69 title: "A new todo",70 done: false71 });72 })73 );74 }, []);7576 return (<div>{*/ See CodeSandbox */}</div>)

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

line 77why, one step back
77}

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

line 78why, one step back
78```

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

line 79why, one step back
79

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 80–81why, one step back
80## useImmer
81

docs: Update example-setstate.mdx (#829)SyedTayyabUlMazharbefore adoptionbc890f7

line 82why, one step back
82Since 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:

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 83–129why, one step back
83
84```javascript85import React, { useCallback } from "react";86import { useImmer } from "use-immer";8788const TodoList = () => {89 const [todos, setTodos] = useImmer([90 {91 id: "React",92 title: "Learn React",93 done: true94 },95 {96 id: "Immer",97 title: "Try Immer",98 done: false99 }100 ]);101102 const handleToggle = useCallback((id) => {103 setTodos((draft) => {104 const todo = draft.find((todo) => todo.id === id);105 todo.done = !todo.done;106 });107 }, []);108109 const handleAdd = useCallback(() => {110 setTodos((draft) => {111 draft.push({112 id: "todo_" + Math.random(),113 title: "A new todo",114 done: false115 });116 });117 }, []);118119 // etc120```121122For the full demo see [CodeSandbox](https://codesandbox.io/s/use-immer-bvd5v?file=/src/index.js).123124## useReducer + Immer125126Similarly 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):127128```javascript129import React, {useCallback, useReducer} from "react"

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

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

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 131–141why, one step back
131
132const TodoList = () => {133 const [todos, dispatch] = useReducer(134 produce((draft, action) => {135 switch (action.type) {136 case "toggle":137 const todo = draft.find(todo => todo.id === action.id)138 todo.done = !todo.done139 break140 case "add":141 draft.push({

docs: Update example-setstate.mdx (#833)VladislavMurashchenkobefore adoption1195510

line 142why, one step back
142 id: action.id,

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 143–153why, one step back
143 title: "A new todo",
144 done: false145 })146 break147 default:148 break149 }150 }),151 [152 /* initial todos */153 ]

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

line 154why, one step back
154 )

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 155–164why, one step back
155
156 const handleToggle = useCallback(id => {157 dispatch({158 type: "toggle",159 id160 })161 }, [])162163 const handleAdd = useCallback(() => {164 dispatch({

docs: Update example-setstate.mdx (#833)VladislavMurashchenkobefore adoption1195510

lines 165–166why, one step back
165 type: "add",
166 id: "todo_" + Math.random()

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 167–170why, one step back
167 })
168 }, [])169170 // etc

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

line 171why, one step back
171}

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 172–191why, one step back
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({

docs: Update example-setstate.mdx (#833)VladislavMurashchenkobefore adoption1195510

line 192why, one step back
192 id: action.id,

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 193–214why, one step back
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```javascript

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

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

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 216–229why, one step back
216
217// 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({

docs: Update example-setstate.mdx (#833)VladislavMurashchenkobefore adoption1195510

line 230why, one step back
230 id: action.id,

docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c

lines 231–238why, one step back
231 title: "A new todo",
232 done: false233 })234 break235 default:236 break237 }238})

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

line 239why, one step back
239```