5 Making React interactive with states

 

This chapter covers

  • The role of state in a component
  • Using state in functional components
  • Converting stateful class-based components to functional components

All the components we have created so far, take some properties and render some HTML based on those properties. We can pass a label property to a button, so the button is displayed with that exact button text, for instance. But we cannot make the button text change, when something happens, such as changing between "Turn on" and "Turn off" when toggled. That’s because we lack both the ability to react to something that happens, as well as the ability to store the single piece of information that something has happened.

The output of the components we have created so far depends on nothing but their properties. In other words, the components are "pure" in functional programming terms. The components have no other inputs and no side effects. If you give the same component the same properties, you will always get the same result and nothing but that result.

5.1 Why is React state relevant?

5.1.1 React component state

5.1.2 Where should I put state?

5.1.3 What kind of information do you store in component state?

5.1.4 What not to store in state

5.2 Adding state to a functional component

5.2.1 Importing and using a hook

5.2.2 Initializing the state

5.2.3 Destructuring the state value and setter

5.2.4 Using the state value

5.2.5 Setting the state

5.2.6 Using multiple states

5.2.7 State scope

5.3 Stateful class-based components

5.3.1 Similarities with useState hook

5.3.2 Differences from useState hook

5.3.3  Conversion to a functional component

5.4 Quiz

5.5 Summary

5.6 Quiz answers

sitemap