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
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>12</center> <details>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>3233## useState + Immer3435The `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).3637```javascript38import React, { useCallback, useState } from "react";39import {produce} from "immer";4041const 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>)77}78```7980## useImmer8182Since 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:8384```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"130import {produce} from "immer"131132const 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({142 id: action.id,143 title: "A new todo",144 done: false145 })146 break147 default:148 break149 }150 }),151 [152 /* initial todos */153 ]154 )155156 const handleToggle = useCallback(id => {157 dispatch({158 type: "toggle",159 id160 })161 }, [])162163 const handleAdd = useCallback(() => {164 dispatch({165 type: "add",166 id: "todo_" + Math.random()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: action.id,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: action.id,231 title: "A new todo",232 done: false233 })234 break235 default:236 break237 }238})239```