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’ve 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 can’t 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 and the ability to store the single piece of information that something has changed dynamically.

The output of the components we’ve 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’ll 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 the useState hook

5.3.2 Differences from the useState hook

sitemap