example-setstate.md
This file
Path
docs/example-setstate.md
34 lines · 734 bytes · Markdown
Last changed by
Docs WIPMichel Weststratebefore adoption12298be
History of this fileTake it
Docs WIPMichel Weststratebefore adoption12298be
lines 1–34why, one step back1---2id: example-setstate3title: React setState example4---56<div id="codefund"><!-- fallback content --></div>78Deep 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)):910```javascript11/**12 * Classic React.setState with a deep merge13 */14onBirthDayClick1 = () => {15 this.setState(prevState => ({16 user: {17 ...prevState.user,18 age: prevState.user.age + 119 }20 }))21}2223/**24 * ...But, since setState accepts functions,25 * we can just create a curried producer and further simplify!26 */27onBirthDayClick2 = () => {28 this.setState(29 produce(draft => {30 draft.user.age += 131 })32 )33}34```