liveBook · Manning

React context

As explained in React Hooks in Action: With Suspense and Concurrent Mode

A context object is a React object that identifies a shared value and provides the associated provider and default-value configuration.

A context object identifies a shared value and connects its provider configuration with components that consume that value. It avoids passing state through intermediate components that do not use it, making it useful when many components across an application need rarely changing information such as the current user, theme, or language. section 8.0 section 8.3

Use a context object through a provider-and-consumer flow:

  • Create and export the object with createContext, optionally supplying a default value. section 8.1.4 section 8.2.4
  • Wrap the component subtree that needs the value with Context.Provider and pass the shared value through its value prop. section 8.1.4 section 8.3
  • Read the value with useContext(Context); consumers re-render when that context value changes. section 8.1.4 section 8.2
  • Split unrelated values into multiple contexts when consumers should update independently, and use custom providers to centralize shared-state management. section 8.2.3 section 8.3

Sharing the current user

Create UserContext with createContext(), provide the current user near the application root with <UserContext.Provider value={user}>, and read it inside BookingDetails with const user = useContext(UserContext). The component can then compare booking.bookerId with user.id and show an edit button only for the current user's booking. section 8.1.4

Listing 8.3 Creating and exporting a context object for our user value
import {createContext} from "react";

const UserContext = createContext();

export default UserContext;

Shows the minimal createContext import, object creation, and export pattern. section 8.1.4

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains creation, provider placement, consumption, defaults, multiple contexts, and re-render implications without descending into React internals.
Examples
Uses a bookings application, current-user selection, booking details, edit-button visibility, themes, languages, and multiple context providers.
What it assumes
Assumes React function components, state, props, and hooks while teaching context-specific provider and consumer usage.
What you can do after
Build it from scratch by creating a context, providing its value, consuming it with useContext, and choosing defaults or split providers.
How it connects
Connects context objects with providers, useContext, custom providers, component composition, props, and state lifting.

Also explained in

Compare how 3 books explain React context →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.