The Road to React Mastery — Understanding State

State in React is an incredibly powerful feature of class-based components and is somewhat similar to React props, but with a few significant differences. State encapsulates the customisable properties and values associated with an instance of a component (whereas props are read only). State is both controllable and private to its individual component, and thus is an incredibly powerful feature of React.

To help you visualise State, imagine that if a component was a person, their skin color, nationality, name etc, are props — generally unchanging attributes that are given to that person by a parent. The state of the component could then be considered to be the clothes that person chooses to wear, dynamic and changeable!

Regardless of if you did or didn’t understand that somewhat poor analogy, let’s get started!

To allow our components to have state, we need to use class-based components, rather than function-based components.

Now we have a scoreboard, that displays the team names, values that are set initially and don’t change, meaning they can be set in the props. However, we now need to integrate their scores, because so far, the board would awkwardly display “Score for team 1 vs Score for team 2” — not very helpful.

This is where state comes in. Let’s incorporate it into our component.

Now we have a scoreboard, that displays each teams’ starting score of 0. Great! It’s much better than the awkward placeholders we had before.

But what happens when someone scores a point? Right now, nothing would. Meaning what we’ve created is essentially a stateless component in the form of a stateful component. So really, not that helpful after all. We need to incorporate a scoring mechanism for this scoreboard to be of any use to anyone.

That’s exactly what we’ll do when we explore both React events and mutating state. So, to learn how to make our state dynamic, and our components much more powerful, check out part 2 below!