ReactEasy
What is useContext?
useContext(SomeContext) reads the value of a React context from the nearest provider above the component, and re-renders the component when that value changes. It is how deeply nested components access shared data such as theme, locale or the current user without prop drilling.
Steps
- Create:
const ThemeContext = createContext<Theme>("light"). The argument is the default value used when there is no provider. - Provide: in React 19, render
<ThemeContext value={theme}>...</ThemeContext>directly (<ThemeContext.Provider>still works but will be deprecated). - Consume:
const theme = useContext(ThemeContext).
React 19's use
use(ThemeContext) does the same, but unlike hooks it can be called inside conditions and loops.
Re-render behavior
- Every component that reads the context re-renders when the provided value changes.
- Passing a new object each render (
value={{ user, setUser }}) re-renders all consumers on every provider render. Memoize the value (useMemo) or let the React Compiler do it. - Split frequently changing values and rarely changing ones into separate contexts.
Best practices
- Wrap context in a custom hook (
useTheme()) that throws a helpful error when used outside its provider. - Use context for low-frequency global values. For high-frequency state shared widely, a store with selectors (Zustand, Redux) avoids broad re-renders.
- React 19.3: Server Components can render a context provider directly from a
"use client"module without a wrapper component (they still cannot create context).
Code example
tsx
1import { createContext, useContext, useMemo, useState } from "react";23type Theme = "light" | "dark";4type ThemeCtx = { theme: Theme; toggle: () => void };56const ThemeContext = createContext<ThemeCtx | null>(null);78export function ThemeProvider({ children }: { children: React.ReactNode }) {9 const [theme, setTheme] = useState<Theme>("light");10 const value = useMemo(11 () => ({ theme, toggle: () => setTheme((t) => (t === "light" ? "dark" : "light")) }),12 [theme]13 );14 return <ThemeContext value={value}>{children}</ThemeContext>; // React 19 provider syntax15}1617export function useTheme() {18 const ctx = useContext(ThemeContext);19 if (!ctx) throw new Error("useTheme must be used inside <ThemeProvider>");20 return ctx;21}2223export function ThemeButton() {24 const { theme, toggle } = useTheme();25 return <button onClick={toggle}>Theme: {theme}</button>;26}
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.