liveBook · Manning

React Context Consumer

As explained in React Quickly, Second Edition

A React Context Consumer is a component that reads a context value and provides it to a child function for rendering.

A React Context Consumer reads the current value from a React context and supplies it to a function that returns JSX. It helps avoid prop drilling when data must reach deeply nested components. section 10.1.1 section 10.1.3

Use a context consumer as follows:

  • Create a context with createContext, optionally supplying a default value. section 10.1.3
  • Place a matching context provider above the components that need the value. section 10.1.1
  • Render Context.Consumer with a function as its only child; React invokes that function with the current context value. section 10.1.3
  • Resolve the nearest matching provider, or receive the context default when no provider is found. section 10.6

Display a context value

function DisplayName() { return ( <p> <NameContext.Consumer> {(name) => name} </NameContext.Consumer> </p> ); } The child function is a render prop: it receives the current name and returns the paragraph content. In functional codebases, useContext is usually shorter and is preferred over the .Consumer property; .Consumer remains especially relevant in older class-based projects. section 10.1.3 section 10.6

How React Quickly, Second Edition covers it

How deep it goes
Explains provider lookup, default values, and render-prop syntax, then defers most use to the useContext hook.
Examples
Uses a DisplayName component that renders a name through NameContext.Consumer.
What it assumes
Assumes basic React components and JSX, while introducing context creation, providers, consumers, and render props.
What you can do after
Apply Context.Consumer to render JSX from a context value, while choosing useContext for newer functional code.
How it connects
Connects React Context Consumer with createContext, context providers, useContext, render props, and prop drilling.

Related concepts

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