React Foundations · Async Data

Reading context with use

use() with context

Reading context with use

A component sometimes needs to bail out early — a Banner that returns nothing when show is false. But useContext is a hook, so it has to run at the top level, before any return, and the early exit blocks it:

// This throws: a hook after an early return.
function Banner({ show }) {
  if (!show) return null;
  const theme = useContext(ThemeContext);
  // ...
}

The use hook reads the same context, but the rule does not apply to it. You can call it conditionally, inside a loop, or after an early return:

import { use } from 'react';

function Banner({ show }) {
  if (!show) return null;
  const theme = use(ThemeContext);
  return <p>{theme}</p>;
}

use(ThemeContext) returns the nearest provider's value, exactly as useContext(ThemeContext) does. The only difference is where the call is allowed. That freedom lets a component guard its expensive work first, then read what it needs on the path that actually runs.

Your job is to read a context value with use after an early return.

Challenge

A banner is meant to read the theme from a context above it, but it is reading the default instead. Export an App component from App.jsx that renders a Banner show child inside <ThemeContext value="dark">. ThemeContext defaults to light. Banner takes a show prop, returns null when show is false, and otherwise reads the theme with use into a paragraph.

The Test renders your component and expects the paragraph to read dark. The starter reads the default light, so the Test fails.

App.jsx
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function Banner() {
  const theme = useContext(ThemeContext);
  return <p>{theme}</p>;
}
export function App() {
  return <Banner />;
}

No test run yet

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