liveBook · Manning

Context value

As explained in React Quickly, Second Edition

A context value is the data stored in React Context and made available to components that consume that context.

A context value is the data supplied through a React context provider and read by components below it. It can be a list, object, function, or stateful value. Components use useContext to read the current value without receiving it through every intermediate component. section 11.4.2 section 11.5.2

Build a context value in three steps:

  • Create and export a context with createContext, choosing a useful default such as an empty list. section 11.4.2
  • Wrap the relevant component subtree in Context.Provider and pass the current data through its value property. section 11.4.2
  • Call useContext inside a descendant component to read the value. section 11.4.2
  • Use an object when the provider must expose several values, such as data and functions. section 11.5.2

Sharing a selected user

const NameContext = createContext(); function UserButton() { const name = useContext(NameContext); return <button>👤 {name}</button>; } function AdminDashboard() { const [name, setName] = useState('Alice'); return ( <NameContext.Provider value={name}> <select value={name} onChange={event => setName(event.target.value)}> <option>Alice</option> <option>Bob</option> <option>Carol</option> </select> <UserButton /> </NameContext.Provider> ); } When name changes, components using the context value re-render automatically, so the dashboard can update its menu and headline together. section 10.1.2

const value = {
  someValue,       #1
  someFunction,    #2
);
return (
  <Context.Provider value={value}>
    ...
  </Context.Provider>
);

An object context value can expose several related values through one provider, including state and functions. section 11.5.2

How React Quickly, Second Edition covers it

How deep it goes
Explains creation, provision, consumption, defaults, objects, custom hooks, and reactive updates, but does not detail performance optimization.
Examples
Uses menu links, an administrator dashboard, selected users, authentication state, API access, and object-shaped provider values.
What it assumes
Assumes basic React components and hooks while teaching context creation, provider placement, default values, and consumer access.
What you can do after
Apply it via React createContext, Context.Provider, useContext, useState, and custom hooks to share changing application data.
How it connects
Connects context values with createContext, Context.Provider, useContext, useState, custom hooks, and component re-rendering.

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 Quickly, Second Edition. The section links point to the parts of the book it draws on.