useContext Hook
上下文 API for sharing 数据跨越组件树 不使用 prop drilling.
你将学到
- problem 的 prop drilling and 如何上下文解决它
- 创建, providing, and consuming 上下文
- 当到 use 上下文对比当 到 use 状态库
- 性能 considerations 使用上下文
概念讲解
The Prop Drilling Problem
When data needs to be accessible by many components at different nesting levels, passing props through every intermediate component is tedious and fragile. This is called prop drilling (or threading). If a deeply nested component needs the current user, you must pass 用户 through every component in between, even if those intermediate components do not use it. This makes refactoring painful and the code harder to follow.
The Context API
React Context solves prop drilling by letting you share data across the entire component tree without passing props manually at every level. You create a context with createContext(defaultValue), provide it high in the tree with <上下文.Provider 值={...}>, and consume it anywhere below with useContext(上下文). The provider creates a scope, and every consumer inside that scope gets the current value.
Creating and Using Context
The typical pattern is to create the context in a separate file, export a custom hook (like useTheme or useAuth) that calls useContext and throws if used outside a provider, and export the provider component. This encapsulates the context and gives a clean API. The provider manages the state and passes both the state and the functions to update it as the context value.
When Not to Use Context
Context is great for low-frequency updates like theme, locale, current user, or authentication status. It is not a replacement for a full state management library. Every consumer of a context re-renders when the context value changes, even if the specific piece they use did not change. For high-frequency updates or complex state logic, consider useReducer with context, or a dedicated state library like Zustand or Redux.
Splitting Contexts
A common optimization is to split a large context into multiple smaller ones. Instead of one AppContext that holds theme, user, and notifications (causing all consumers to re-render on any change), create separate ThemeContext, UserContext, and NotificationContext. Each consumer only re-renders when its specific context changes. This granularity keeps re-renders minimal.
示例代码
import { createContext, useContext, useState } from "react";
// 1. Create the context.
const ThemeContext = createContext();
// 2. Custom hook for consuming the context.
function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error("useTheme must be used within ThemeProvider");
return ctx;
}
// 3. Provider component that manages state.
function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
const toggle = () => setTheme(t => t === "light" ? "dark" : "light");
return (
<ThemeContext.Provider value={{ theme, toggle }}>
{children}
</ThemeContext.Provider>
);
}
// 4. Consumer — no prop drilling needed.
function Header() {
const { theme, toggle } = useTheme();
return (
<header className={theme}>
<button onClick={toggle}>Switch to {theme === "light" ? "dark" : "light"}</button>
</header>
);
}
ThemeContext 是创建, provided 通过 ThemeProvider, and consumed 通过请求头通过 useTheme Hook. 否 Props 是通过通过中级组件.
动手试一试
- JSON Formatter
上下文值 是经常对象 — 格式它们到 inspect shape.
- Code Diff
Compare 上下文 provider implementations 当 refactoring.
常见错误
错误写法
Using 上下文 for 高-frequency 状态更新
正确做法
每个上下文 consumer re-渲染当 值更改. For 频繁更新, 拆分上下文通过 concern, use useReducer, or 选择状态库 如 Zustand 那个 supports selective subscriptions.
错误写法
创建新 对象 as 上下文值 on 每个渲染
正确做法
如果 provider 创建新 对象值={{ , b }} on 每个渲染, 所有 consumers re-渲染每个时间. Memoize 值使用 useMemo or 拆分到 多个 providers.
练习 useContext Hook
9 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。