example-setstate.mdx
This file
Path
website/docs/example-setstate.mdx
240 lines · 5.4 KiB
Last changed by
docs: Update example-setstate.mdx (#833)VladislavMurashchenkobefore adoption1195510
History of this fileTake it
docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 1–2why, one step back1---2id: example-setstatedocs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
line 3why, one step back3title: React & Immerdocs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 4–11why, one step back4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 12–13why, one step back12</center>13<details>docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 14–33why, one step back14 <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>33docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
line 34why, one step back34## useState + Immerdocs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
line 35why, one step back35docs: Update example-setstate.mdx (#829)SyedTayyabUlMazharbefore adoptionbc890f7
line 36why, one step back36The `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 37why, one step back37docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
line 38why, one step back38```javascriptdocs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 39–77why, one step back39import 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>)docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
line 78why, one step back78}docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
line 79why, one step back79```docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
line 80why, one step back80docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 81–82why, one step back81## useImmer82docs: Update example-setstate.mdx (#829)SyedTayyabUlMazharbefore adoptionbc890f7
line 83why, one step back83Since 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 84–142why, one step back8485```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({docs: Update example-setstate.mdx (#833)VladislavMurashchenkobefore adoption1195510
line 143why, one step back143 id: action.id,docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 144–154why, one step back144 title: "A new todo",145 done: false146 })147 break148 default:149 break150 }151 }),152 [153 /* initial todos */154 ]docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
line 155why, one step back155 )docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 156–165why, one step back156157 const handleToggle = useCallback(id => {158 dispatch({159 type: "toggle",160 id161 })162 }, [])163164 const handleAdd = useCallback(() => {165 dispatch({docs: Update example-setstate.mdx (#833)VladislavMurashchenkobefore adoption1195510
lines 166–167why, one step back166 type: "add",167 id: "todo_" + Math.random()docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 168–171why, one step back168 })169 }, [])170171 // etcdocs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
line 172why, one step back172}docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 173–192why, one step back173```174175## useImmerReducer176177...which again, can be slightly shorted by `useImmerReducer` from the `use-immer` package ([demo](https://codesandbox.io/s/useimmerreducer-sycpb?file=/src/index.js)):178179```javascript180import React, { useCallback } from "react";181import { useImmerReducer } from "use-immer";182183const TodoList = () => {184 const [todos, dispatch] = useImmerReducer(185 (draft, action) => {186 switch (action.type) {187 case "toggle":188 const todo = draft.find((todo) => todo.id === action.id);189 todo.done = !todo.done;190 break;191 case "add":192 draft.push({docs: Update example-setstate.mdx (#833)VladislavMurashchenkobefore adoption1195510
line 193why, one step back193 id: action.id,docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 194–230why, one step back194 title: "A new todo",195 done: false196 });197 break;198 default:199 break;200 }201 },202 [ /* initial todos */ ]203 );204205 //etc206207```208209## Redux + Immer210211Redux + 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!212213For example:214215```javascript216import produce from "immer"217218// Reducer with initial state219const INITIAL_STATE = [220 /* bunch of todos */221]222223const todosReducer = produce((draft, action) => {224 switch (action.type) {225 case "toggle":226 const todo = draft.find(todo => todo.id === action.id)227 todo.done = !todo.done228 break229 case "add":230 draft.push({docs: Update example-setstate.mdx (#833)VladislavMurashchenkobefore adoption1195510
line 231why, one step back231 id: action.id,docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 232–239why, one step back232 title: "A new todo",233 done: false234 })235 break236 default:237 break238 }239})docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
line 240why, one step back240```