React Holiday

Day 9: Set state dynamically

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.

Concise but not clear

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.

Why 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.

I’m so confused…

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)

Tinker with it

Use the workspace below and set some state with functions.