Skip to content
Myr

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 file

Take it

Show the source

example-setstate.md


id: example-setstate title: React setState example

Deep 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):

/**
 * Classic React.setState with a deep merge
 */
onBirthDayClick1 = () => {
	this.setState(prevState => ({
		user: {
			...prevState.user,
			age: prevState.user.age + 1
		}
	}))
}

/**
 * ...But, since setState accepts functions,
 * we can just create a curried producer and further simplify!
 */
onBirthDayClick2 = () => {
	this.setState(
		produce(draft => {
			draft.user.age += 1
		})
	)
}