React Foundations ยท Composition

Sharing data with context

Context

Sharing data with context

When you pass a value down through many layers of props, each layer in between has to accept it and hand it on. That is prop drilling. Context lets a value skip the middle layers: a provider makes it available, and any descendant reads it directly.

const ThemeContext = createContext('light');

function Label() {
  const theme = useContext(ThemeContext);
  return <p>{theme}</p>;
}

function App() {
  return (
    <ThemeContext value="dark">
      <Label />
    </ThemeContext>
  );
}

createContext takes a default value, used when there is no provider above. Since React 19 you can render <ThemeContext value={...}> directly to supply the real value to everything inside it; the older <ThemeContext.Provider value={...}> still works but is on its way out. useContext(ThemeContext) reads the nearest provider's value.

Label never receives a prop, yet it renders dark. That is the point: the value travels through the tree without being threaded through every component.

Your job is to provide a value and read it in a child.

Challenge

A theme is hard-coded to light, so every child shows the wrong one. Export an App component from App.jsx that provides the value dark on a context and renders a child component that reads it with useContext into a paragraph.

The Test renders your component and looks for a paragraph reading dark. The starter hard-codes light, so the Test fails. Supply the value from a provider.

App.jsx
export function App() {
  return <p>light</p>;
}

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.