liveBook · Manning

useContext

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

useContext is a React Hook that reads the current value from a React context.

useContext reads a context value inside a function component, avoiding prop passing through intermediary components. A Provider supplies the value to a subtree, and consumers update when that value changes. section 8.0 section 8.3

Use useContext as part of a context-sharing workflow:

  • Create and export a context object with createContext. section 8.1.4
  • Wrap the component subtree that needs the value in the context’s Provider and pass value to it. section 8.1.4
  • Call useContext with the context object to read the current value. section 8.3
  • Supply a default when creating the context if consumers may render without a matching Provider. section 8.2.4
  • Split unrelated shared values across multiple contexts, and consider custom providers for shared state management. section 8.3

Showing a booking edit control for the current user

A bookings interface shares the current user from App through UserContext. BookingDetails reads it with useContext and derives whether the booking belongs to that user: const user = useContext(UserContext); const isBooker = booking && user && (booking.bookerId === user.id); The edit button renders only when isBooker is true. Selecting another user updates the Provider value, so the consuming booking component re-renders with the new permission result. section 8.1.4

const localValue = useContext(MyContext);

Inspect the minimal consumer expression: pass the context object to useContext and store the returned value locally. section 8.3

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

How deep it goes
Explains creation, Provider placement, consumption, defaults, re-renders, and context splitting, while deferring implementation internals.
Examples
Uses a bookings application where BookingDetails reads the current user and conditionally displays an edit button.
What it assumes
Assumes function components and Hooks, while introducing context objects, Providers, consumers, defaults, and shared-state boundaries.
What you can do after
Apply it via React to provide shared values and read them in function components without threading props through unrelated layers.
How it connects
Ties useContext to React Hooks, createContext, context providers, shared state, component re-rendering, custom providers, and the children prop.

Also explained in

Compare how 2 books explain useContext →

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.