chapter three

3 Managing component state with the useState hook

 

This chapter covers

  • Asking React to manage component state values by calling useState
  • Changing state values and triggering re-renders with an updater function
  • Using the previous state to help generate new state values
  • Managing multiple pieces of state
  • Considering how React and components interact to persist and update state and synchronize state and UI

If you’re building React apps, then you’re expecting the data your app uses to change over time. Whether it’s fully server-rendered, a mobile app or all in a browser, your application’s user interface should represent the current data or state at the time of rendering. Sometimes multiple components throughout the app will use the data, and sometimes a component doesn’t need to share its secrets and can manage its own state without the help of mammoth, application-wide state-store behemoths. In this chapter, we’ll keep it personal and concentrate on components taking care of themselves, without regard for other components around them.

3.1   A bookings manager: setting up the App

3.1.1   Generating the app skeleton with create-react-app

3.1.2   Editing the four key files

3.1.3   Adding a database file for the application

3.1.4   Creating a components folder and a Bookables.js file

3.2   Storing, using and setting values with useState

3.2.1   Assigning new values to variables doesn’t update the UI

3.2.2   Calling useState returns a value and an updater function

3.2.3   Calling the updater function replaces the previous state value

3.2.4   Passing a function to useState as the initial value

3.2.5   Using the previous state when setting the new state

3.3   Calling useState multiple times to work with multiple values

3.3.1   Using a drop-down list to set state

3.3.2   Using a checkbox to set state

3.4   Reviewing some function component concepts

3.5   Summary