liveBook · Manning

Context value

As explained in React in Depth

A context value is the data supplied by a React context provider for access by consuming components.

A context value is the data exposed by a React provider to consuming components. It can be a primitive such as a dark-mode Boolean or an object combining state with actions such as a toggle function. section 2.1.1 section 6.1.3

Design the value with these implementation concerns in mind:

  • Keep related data and operations together when consumers need both; the dark-mode example supplies isDarkMode and toggleDarkMode in one object. section 2.1.1
  • Expect every consumer to re-render when the context changes. Memoize components that do not consume the context to limit unrelated updates. section 2.1.1
  • Let TypeScript infer simple values from createContext defaults, or provide a generic type for nullable, structured values. section 6.1.3
  • Use useContext to retrieve the value in the demonstrated syntax. React 19 also supports a context element with value and consumption through use(). section 2.1.1 section 6.1.3

Typed dark-mode context

Define a context as DarkModeContext = createContext<DarkMode | null>(null), where DarkMode contains mode and toggle. Provide the current value from App, then consume it through a checked useDarkMode helper; components such as Button can read mode without receiving it through every prop. section 6.1.3

Figure 2.3 A document tree sketch of our website with a dark mode/light mode toggle. Note how we pass in an object to the context provider (dashed box), which we can deconstruct and use wherever we need either of the two values in the components below the provider in the document tree.
figure

A document-tree sketch shows how one provider-supplied object distributes dark-mode state and its toggle action to components below it. section 2.1.1

How React in Depth covers it

How deep it goes
Explains object values, consumer re-renders, memoization, TypeScript inference, and explicit context typing; it stops short of selector-based contexts.
Examples
Uses light/dark mode with a Boolean value, then an object containing mode and toggle.
What it assumes
Assumes React fundamentals and TypeScript basics; teaches context-value typing from inferred Boolean values through generic object types.
What you can do after
Build it from scratch by defining, providing, consuming, typing, and performance-tuning a context value.
How it connects
Connects context values to providers, consumers, useContext, use(), memoization, state, and TypeScript types.

Also explained in

Compare how 2 books explain context value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.