Skip to content
Myr

example-setstate.md

This file

Path

docs/example-setstate.md

43 lines · 1.3 KiB · Markdown

Last changed by

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

History of this file

Take it

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

lines 1–43why, one step back
1---
2id: example-setstate3title: React setState example4---56<div id="codefund"><!-- fallback content --></div>78<details>9 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 8: Using Immer with _useState_. Or: _useImmer_</summary>10 <br>11 <div style="padding:5px;">12 <iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-immutable-update-state-inside-react-components-with-useimmer/embed" ></iframe>13 </div>14 <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>15</details>1617Deep 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)):1819```javascript20/**21 * Classic React.setState with a deep merge22 */23onBirthDayClick1 = () => {24 this.setState(prevState => ({25 user: {26 ...prevState.user,27 age: prevState.user.age + 128 }29 }))30}3132/**33 * ...But, since setState accepts functions,34 * we can just create a curried producer and further simplify!35 */36onBirthDayClick2 = () => {37 this.setState(38 produce(draft => {39 draft.user.age += 140 })41 )42}43```