⚛️🌲 React Holiday


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.

Day 8: Set state statically

December 08, 2017

Managing state is hard.

I’ll take four days to cover the React APIs for setting state.
So don’t read today’s lesson without coming back for set state dynamically and setState is a food truck.

setState is GrrrrREAT!

Meet setState().

this.setState({ someProp: newState })

This is a special power our components get by extending React.Component.
When called, setState updates the local state object and re-renders the component.

Set state statically

Continue yesterday’s example and replace the alert with a proper state change.

<button
  type="button"
  onClick={() =>
    this.setState({ clapCount: 1 })
  }
>
  {this.state.clapCount}
  {' '}👏
</button>

Limitations

Above, we call setState() with a new state object.

There are two ways to use setState. This one is easy to understand but quickly limiting. We set clapCount with a static value but how do we use a dynamic value? How do we keep our counter counting, transitioning current state to the next state?

Tomorrow we’ll learn how to transition state.

Tinker with it

Use the workspace below and set some state.

  • Change value you set clapCount to. Get crazy; try a string.
  • Create another component that counts something else. 👍s, 🙌s, anything!
  • Keep the counter counting. Try your hand at making state changes dynamic.

chantastic

Written by chantastic.
Follow his nonsense on Twitter.