8 Managing state with the Context API

 

This chapter covers

  • Providing state via the Context API and its Provider component
  • Consuming context state with the useContext hook
  • Avoiding unnecessary re-renders when updating state values
  • Creating custom context providers
  • Splitting shared state across multiple contexts

We’ve seen state encapsulated within components, lifted to shared parents, in form fields, persisted across renders, and pulled in from a database, and we’ve used a whole bunch of hooks to help us set up and work with that state. Our approach has been to keep the state as close to the components that use it as possible. But it’s not uncommon for many components, nested on multiple branches, to hunger for the same juicy worms, the same tidbits of application state, like themes, localization info, or authenticated user details. Mmmmmmm, tidbits . . . React’s Context API is a way of delivering juicy state tidbits directly to your nest without passing them down through multiple layers of intermediaries who, preferring tacos to tidbits, have no interest in them.

8.1 Needing state from higher up the component tree

8.1.1 Displaying a call-to-action message when the page first loads

8.1.2 Displaying booking information when a visitor selects a booking

8.1.3 Displaying an edit button for a user’s bookings: The problem

8.1.4 Displaying an edit button for a user’s bookings: The solution

8.2 Working with custom providers and multiple contexts

8.2.1 Setting an object as the context provider’s value

8.2.2 Moving the state to a custom provider

8.2.3 Working with multiple contexts

8.2.4 Specifying a default value for a context

Summary