React

Understanding "state" in React Components

PRO
Outline

What is state?

The heart of every React component is its “state”, an object that determines how that component renders & behaves. In other words, “state” is what allows you to create components that are dynamic and interactive.

If you’re not familiar with the idea of state machines (what React “state" is modeled after), this all might seem a bit abstract. However, this couldn’t be further from the truth. You’ve interacted with state-based systems your entire life — you just haven’t realized it!

A quick analogy to explain state

This might seem trivial, but please take a moment to consider this question: What’s the difference between water and ice?

That’s right — the temperature! Now, let's go one level deeper: what is “temperature”? The answer is that it’s a measurement of thermal energy — the key word for us being measurement, because that implies it is tracked with a known value (any number between absolute zero and absolute hot).

If you think about it, that’s kind of incredible. If you can change the value on a thermometer, that means you have the ability to put a piece of matter into a different state. With water, simply put it in your freezer (below 32F) and its state will change from liquid to a solid. If you put it on a hot stovetop (above 212F), its state will change from liquid to gas. All of this can be done just by changing one value: its temperature.

What if we could do the same thing with programs? What if we could define a set of properties that would determine how our program would behave in any situation, similarly to water’s relationship with temperature?

 

I finished! On to the next chapter