C
React/Hooks/Lesson 13

useContext

30 min·theory
This chapter
5/5
JavaScript

useContext

💡 Why should you learn this?

🎯 You can easily share global data such as login information and theme settings.
💼 It eliminates the complexity of passing props through 5 or 10 levels of components.
You can build small-to-medium projects quickly without complex state management libraries like Redux.
🏢 실무에서는
In real-world development, useContext is used to manage app-wide data such as user information, dark mode settings, and language preferences. It is typically the first pattern new engineers learn when joining a team.

What is useContext?

useContext

A Hook that shares data across the entire component tree via the Context API.

The Props Drilling Problem

code
App → Layout → Sidebar → UserMenu → UserAvatar (5 levels deep)

With Context, any component can access the data directly without passing it through intermediate components.

Changes in React 19

  • Can be used more concisely with the use(Context) Hook
  • Context default values can be used without a Provider
💻 useContext in Practice
import { createContext, useContext, useState, ReactNode } from "react";

// 1. Create Context
interface ThemeContextType {
  theme: "light" | "dark";
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType | null>(null);

// 2. Provider Component
function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<"light" | "dark">("dark");
  const toggleTheme = () => setTheme(t => t === "light" ? "dark" : "light");

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// 3. Custom Hook (type-safe)
function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) throw new Error("useTheme must be used within ThemeProvider");
  return context;
}

// 4. Usage
function ThemeToggle() {
  const { theme, toggleTheme } = useTheme();
  return (
    <button onClick={toggleTheme} className="p-2 rounded">
      {theme === "dark" ? "🌙" : "☀️"}
    </button>
  );
}

// 5. Wrap App with Provider
function App() {
  return (
    <ThemeProvider>
      <Header />
      <Main />
    </ThemeProvider>
  );
}

// React 19: use() Hook
import { use } from "react";
function NewComponent() {
  const { theme } = use(ThemeContext)!; // React 19 new syntax
  return <div className={theme}>...</div>;
}

💡 💡 Context Tips

  • Custom Hooks: Wrap in hooks like useTheme(), useAuth()
  • Separation: Split Context for frequently changing vs. stable values
  • Alternative: For complex global state, Zustand is more convenient
  • React 19: Conditional reads are possible with use(Context)

This concept is fundamental to React component development. Understand React's declarative UI paradigm and clearly distinguish between props and state. A component should behave like a pure function — always returning the same output (JSX) for the same input (props).

⚛️ React Pattern — useContext

Learn step by step how to use useContext in React, with code examples.
1 📦 1. Create a Context
A data store for globally shared values
const ThemeContext = createContext('light');
2 🎁 2. Wrap with a Provider
Define the scope of the tree that receives the value
<ThemeContext.Provider value="dark">
  <App />
</ThemeContext.Provider>
3 📥 3. Consume with useContext
Direct access from any child, no matter how deeply nested
const theme = useContext(ThemeContext);
4 💡 4. When to use it
Only for truly global state like themes, authenticated users, or locale settings

🌍 useContext — Global State

Edits to the code are reflected automatically after 0.7 seconds. Runs instantly in the browser with React 18 + Babel.
🖥️ Result — rendered React component
✏️ React 코드 수정하기 (클릭해서 열기)
⚛️ React 18 + Babel Standalone — see the result first, then edit the code yourself.

Knowledge Check

What are the drawbacks of useContext?
💡 useContext is convenient for simple global state sharing, but when a Context value changes, every component subscribed to that Context will re-render. For frequently changing state, external state libraries such as Zustand or Jotai offer better performance.
Read this first: Custom Hooks
Up next: React Router
useContext - React