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
const LocaleContext = createContext("en"): the argument is the default when no provider is found.<LocaleContext value={locale}>{children}</LocaleContext>(or<LocaleContext.Provider value>before React 19).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 withuseMemo. - 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
useStateoruseReducerfor 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";23type Locale = "en" | "hi" | "fr";4const LocaleContext = createContext<{ locale: Locale; setLocale: (l: Locale) => void } | null>(null);56export 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}1112export function useLocale() {13 const ctx = use(LocaleContext);14 if (!ctx) throw new Error("useLocale must be used inside <LocaleProvider>");15 return ctx;16}1718const greetings: Record<Locale, string> = { en: "Hello", hi: "नमस्ते", fr: "Bonjour" };1920export 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.