React Foundations · TypeScript

Typing context

Typing context

createContext takes a default value, and TypeScript infers the context's type from it. Infer from a placeholder and every consumer reads the placeholder's shape, not the real one. Name the value's shape with a type argument:

interface ThemeValue {
  theme: string;
}

const ThemeContext = createContext<ThemeValue>({ theme: 'light' });

Now useContext(ThemeContext) returns a ThemeValue, so theme is a string and a misspelled field is a compile error at the read.

Wrap that read in a custom hook so components never touch the context object directly:

function useTheme(): string {
  return useContext(ThemeContext).theme;
}

The hook's return type documents what it hands back, and every component that calls useTheme() gets the same typed value. When the context value grows, only the hook changes and call sites stay the same. The type argument is what makes the read safe — without it the compiler cannot check the fields you pull out.

Your job is to type a context and read it through a custom hook in App.tsx.

Challenge

A context hands a value to a child without props, and it should carry a known type. Export an App component from App.tsx that provides { theme: 'dark' } on a context typed with a ThemeValue interface, and renders a Label child that reads the theme through a useTheme() custom hook into a paragraph.

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

App.tsx
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.