2 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, 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 keep it personal and concentrate on components taking care of themselves, without regard for other components around them.

2.1 Setting up the bookings manager app

2.1.1 Generating the app skeleton with create-react-app

2.1.2 Editing the four key files

2.1.3 Adding a database file for the application

2.1.4 Creating page components and a UserPicker.js file

2.2 Storing, using, and setting values with useState

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

2.2.2 Calling useState returns a value and an updater function

2.2.3 Calling the updater function replaces the previous state value

2.2.4 Passing a function to useState as the initial value

2.2.5 Using the previous state when setting the new state

2.3 Calling useState multiple times to work with multiple values

2.3.1 Using a drop-down list to set state

2.3.2 Using a check box to set state

2.4 Reviewing some function component concepts