We'll start from basics and get all the way to Suspense, Hooks, and advanced composition!
Each day is a 2-3 minute read with CodeSandbox and quick assignments.
Check out 2017 (below) for examples.
December 09, 2017
If you want to set state dynamically, use a function.
this.setState(function(previousState) {
return { someProp: previousState.someProp + 1 }
})
We give setState
an anonymous function to be called with state
.
Our function takes that state
and returns a new object with new values derived from the old.
This is how I write setState(fn)
in a modern code base.
It’s how you’re likely to see it in the real world.
this.setState((previousState) =>
({ clapCount: previousState.clapCount + 1 })
)
Arrow functions have implicit returns but if the return type is an object, you must wrap it in parentheses.
previousState
not currentState
?While setState
does update state—eventually—it does so asynchronously and in batches.
Because of that implementation detail, the state that your function receives might not be the current state.
Yeah. It’s very confusing.
Tomorrow let’s implement our own state setter.
You’ll get a better idea of how setState
sausage is made.
(I’ll use an actual sausage to illustrate)
Use the workspace below and set some state with functions.
state
object.Written by chantastic.
Follow his nonsense on Twitter.