3 Managing component state with the useReducer hook

 

This chapter covers

  • Asking React to manage multiple, related state values by calling useReducer
  • Putting component state management logic in a single location
  • Updating state and triggering re-renders by dispatching actions to a reducer
  • Initializing state with initialization arguments and initialization functions

As your applications grow, it’s natural for some components to handle more state, especially if they supply different parts of that state to multiple children. When you find you always need to update multiple state values together or your state update logic is so spread out that it’s hard to follow, it might be time to define a function to manage state updates for you: a reducer function.

A simple, common example is for loading data. Say a component needs to load posts for a blog on things to do when stuck at home during a pandemic. You want to display loading UI when new posts are requested, error UI if a problem arises, and the posts themselves when they arrive. The component’s state includes values for the following:

  • The loading state—Are you in the process of loading new posts?
  • Any errors—Has an error been returned from the server, or is the network down?
  • The posts—A list of the posts retrieved.

3.1 Updating multiple state values in response to a single event

3.1.1 Taking users out of the movie with unpredictable state changes

3.1.2 Keeping users in the movie with predictable state changes

3.2 Managing more complicated state with useReducer

3.2.1 Updating state using a reducer with a predefined set of actions

3.2.2 Building a reducer for the BookablesList component

3.2.3 Accessing component state and dispatching actions with useReducer

3.3 Generating the initial state with a function

3.3.1 Introducing the WeekPicker component

3.3.2 Creating utility functions to work with dates and weeks

3.3.3 Building the reducer to manage dates for the component

sitemap