React Holiday

Day 8: Set state statically

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.

  onClick={() =>
    this.setState({ clapCount: 1 })
  {' '}👏


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.