Skip to content
Myr

example-setstate.mdx

This file

Path

website/docs/example-setstate.mdx

59 lines · 1.3 KiB

Last changed by

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

History of this file

Take it

1---2id: example-setstate3title: React setState example4---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>3233Deep 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)):3435```javascript36/**37 * Classic React.setState with a deep merge38 */39onBirthDayClick1 = () => {40	this.setState(prevState => ({41		user: {42			...prevState.user,43			age: prevState.user.age + 144		}45	}))46}4748/**49 * ...But, since setState accepts functions,50 * we can just create a curried producer and further simplify!51 */52onBirthDayClick2 = () => {53	this.setState(54		produce(draft => {55			draft.user.age += 156		})57	)58}59```