React 的 Context API 让你与整个 component 子树共享一个值,而无需 prop drilling。它非常适合 低频率、广泛共享 的数据——但它不是一个完整的状态管理解决方案,并且对于频繁变化的状态有一个 re-render 陷阱。
Context 的优势所在
jsx
= ();
() {
[theme, setTheme] = ();
(
);
}
Good fits (data that's read widely but changes rarely):
✓ Theme (dark/light) ✓ Current user / auth
✓ Locale / i18n ✓ App-wide config or feature flags
// ❌ a context value that changes often re-renders ALL consumers
const AppContext = createContext();
// value = { user, cart, notifications, ...everything }
// → updating ONE field re-renders EVERY component using the context
当 context 值改变时,所有 使用该 context 的 component 都会重新渲染——无论它们是否使用了变化的部分。对于频繁更新的状态,这会导致性能问题。Context 没有内置的选择性订阅。
✓ Split into multiple focused contexts (ThemeContext, UserContext separately)
✓ Memoize the value object (useMemo) so it doesn't change identity needlessly
✗ But for high-frequency or large shared state → use a real store
状态库(Zustand、Redux、Jotai)通过 选择性订阅 解决了 re-render 问题——component 仅订阅它们使用的 slice,并仅在这些 slice 改变时重新渲染:
const count = useStore(s => s.count); // re-renders ONLY when count changes
Context = a TRANSPORT mechanism (passes a value down), NOT state management itself.
You still need useState/useReducer to hold the state; Context just distributes it.
了解 Context 的优势——以及它的局限——可以防止两个常见的错误:对应该在 Context 中的东西进行 prop-drilling,以及在 Context 中放置高频率状态(导致应用范围内的 re-render)。
规则:Context 用于 很少变化、广泛共享 的值(主题、用户、语言环境);为 频繁变化或大型 共享状态使用具有选择性订阅的专用存储。
理解 Context 分发状态但不管理状态,可以明确何时足够以及何时需要更多。