Skip to content
Myr

example-setstate.md

This file

Path

docs/example-setstate.md

45 lines · 1.4 KiB · Markdown

Last changed by

docs: updated sponsor linksMichel Weststratebefore adoptionf97d037

History of this file

Take it

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 1–5why, one step back
1---
2id: example-setstate3title: React setState example4---5

docs: updated sponsor linksMichel Weststratebefore adoptionf97d037

lines 6–8why, one step back
6<center>
7<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>8</center>

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

line 9why, one step back
9

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 10–13why, one step back
10<details>
11 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 8: Using Immer with _useState_. Or: _useImmer_</summary>12 <br>13 <div style="padding:5px;">

docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585

line 14why, one step back
14 <iframe style="border: none;" width=760 height=427 scrolling="no" src="https://egghead.io/lessons/react-immutable-update-state-inside-react-components-with-useimmer/embed" ></iframe>

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 15–18why, one step back
15 </div>
16 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/react-immutable-update-state-inside-react-components-with-useimmer">Hosted on egghead.io</a>17</details>18

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 19–45why, one step back
19Deep updates in the state of React components can be greatly simplified as well by using immer. Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):
2021```javascript22/**23 * Classic React.setState with a deep merge24 */25onBirthDayClick1 = () => {26 this.setState(prevState => ({27 user: {28 ...prevState.user,29 age: prevState.user.age + 130 }31 }))32}3334/**35 * ...But, since setState accepts functions,36 * we can just create a curried producer and further simplify!37 */38onBirthDayClick2 = () => {39 this.setState(40 produce(draft => {41 draft.user.age += 142 })43 )44}45```