React: From Components to Production · Sharing State and Structuring Apps

Context for Shared Values

Provide app-wide values like theme, auth and settings without prop drilling.

Context passes values deep into the tree without prop drilling: create it, wrap a subtree in a provider (in React 19 you can render <ThemeContext value={...}> directly), and read it with useContext or React 19's use(Context). All consumers re-render when the value changes, so keep context values stable (useMemo) and split rarely-changing and frequently-changing data into separate contexts.

import { createContext, use, useMemo, useState, type ReactNode } from "react";

type Theme = "light" | "dark";
const ThemeContext = createContext<{ theme: Theme; toggle: () => void } | null>(null);

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>("light");
  const value = useMemo(() => ({ theme, toggle: () => setTheme((t) => (t === "light" ? "dark" : "light")) }), [theme]);
  return <ThemeContext value={value}>{children}</ThemeContext>;
}

export function useTheme() {
  const ctx = use(ThemeContext);
  if (!ctx) throw new Error("useTheme must be used within ThemeProvider");
  return ctx;
}

Common pitfalls

  • Putting fast-changing state (e.g., form input) in a global context, re-rendering everything.
  • Creating a new value object every render.
  • Using context as a replacement for server-state caching.

Key points

  • Context avoids prop drilling
  • Memoize values; split contexts
  • Throw helpful errors outside providers

Further reading: react.dev: Context

Practice questions

Why can a context provider cause performance problems?

Answer

Every consumer re-renders when the provided value changes; a new object each render or frequently changing values re-render large parts of the app.

What's a good use of context?

Answer

Values many components need that change infrequently: theme, current user, locale, feature flags, or dependency injection of services.

Open in the app to mark lessons complete, take notes and track your progress.