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 fileTake it
The walk stopped after 200 commits: lines older than b7fcf7f point at it.
docs: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f
lines 1–2why, one step back1---2id: example-setstatedocs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
line 3why, one step back3title: React & Immerdocs: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f
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>Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 12why, one step back12</center> <details>docs: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f
lines 13–32why, one step back13 <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>32docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
line 33why, one step back33## useState + Immerdocs: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f
line 34why, one step back34docs: Update example-setstate.mdx (#829)SyedTayyabUlMazharbefore adoptionbc890f7
line 35why, one step back35The `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 back36docs: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f
line 37why, one step back37```javascriptdocs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
line 38why, one step back38import React, { useCallback, useState } from "react";Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 39why, one step back39import {produce} from "immer";docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 40–76why, one step back4041const 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: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f
line 77why, one step back77}docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
line 78why, one step back78```docs: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f
line 79why, one step back79docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 80–81why, one step back80## useImmer81docs: Update example-setstate.mdx (#829)SyedTayyabUlMazharbefore adoptionbc890f7
line 82why, one step back82Since 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 back8384```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 back130import {produce} from "immer"docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 131–141why, one step back131132const 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 back142 id: action.id,docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 143–153why, one step back143 title: "A new todo",144 done: false145 })146 break147 default:148 break149 }150 }),151 [152 /* initial todos */153 ]docs: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f
line 154why, one step back154 )docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 155–164why, one step back155156 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 back165 type: "add",166 id: "todo_" + Math.random()docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 167–170why, one step back167 })168 }, [])169170 // etcdocs: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f
line 171why, one step back171}docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 172–191why, one step back172```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 back192 id: action.id,docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 193–214why, one step back193 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```javascriptMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 215why, one step back215import {produce} from "immer"docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 216–229why, one step back216217// 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 back230 id: action.id,docs: Extended / updated documenation (#824)Michel Weststratebefore adoption847492c
lines 231–238why, one step back231 title: "A new todo",232 done: false233 })234 break235 default:236 break237 }238})docs: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f
line 239why, one step back239```