ReactEasy

What is Context API?

The Context API lets a component provide a value that any descendant can read directly, without passing props through every level. You create a context with createContext, provide a value by rendering the context (React 19: <MyContext value={...}>), and read it with useContext(MyContext) or use(MyContext).

Three steps

  1. const LocaleContext = createContext("en"): the argument is the default when no provider is found.
  2. <LocaleContext value={locale}>{children}</LocaleContext> (or <LocaleContext.Provider value> before React 19).
  3. const locale = useContext(LocaleContext) in any descendant.

Good use cases

Theme, locale, current user, feature flags, dependency injection (API clients), and state for compound components (Tabs, Accordion).

Behavior to know

  • All consumers re-render when the value changes (by Object.is). Memoize object values with useMemo.
  • The nearest provider wins; providers can be nested to override values.
  • Context is not a state manager by itself. It distributes a value; pair it with useState or useReducer for updates.

Patterns

  • Export a custom hook (useLocale()) that throws when used outside the provider.
  • Split state and dispatch into two contexts so components that only dispatch do not re-render on state changes.
  • React 19.3: Server Components can render providers exported from "use client" modules directly.

When to use a store instead

Frequently changing values read by many components (cursor positions, large normalized data): stores like Zustand or Redux let components subscribe to slices.

Code example

tsx
1import { createContext, use, useMemo, useState } from "react";
2
3type Locale = "en" | "hi" | "fr";
4const LocaleContext = createContext<{ locale: Locale; setLocale: (l: Locale) => void } | null>(null);
5
6export function LocaleProvider({ children }: { children: React.ReactNode }) {
7 const [locale, setLocale] = useState<Locale>("en");
8 const value = useMemo(() => ({ locale, setLocale }), [locale]);
9 return <LocaleContext value={value}>{children}</LocaleContext>;
10}
11
12export function useLocale() {
13 const ctx = use(LocaleContext);
14 if (!ctx) throw new Error("useLocale must be used inside <LocaleProvider>");
15 return ctx;
16}
17
18const greetings: Record<Locale, string> = { en: "Hello", hi: "नमस्ते", fr: "Bonjour" };
19
20export function Greeting() {
21 const { locale, setLocale } = useLocale();
22 return (
23 <p>
24 {greetings[locale]}{" "}
25 <select value={locale} onChange={(e) => setLocale(e.target.value as Locale)}>
26 <option value="en">EN</option><option value="hi">HI</option><option value="fr">FR</option>
27 </select>
28 </p>
29 );
30}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app