DrillLab
第 82 / 105 道82 / 105 · #349

Redux vs Context API

Redux vs Context API

先自己答,再往下看Answer it yourself first

一句话(这句最关键):它们解决的不是同一个问题。Context 是「传递」方案 (怎么把值送到深处), Redux 是「状态管理」方案 (状态怎么组织、怎么改、怎么调试)。

「Context 能不能替代 Redux」—— 严格说,Context + useReducer可以覆盖 Redux 的基本功能, 但缺三样东西:

  • 没有精细的订阅。context 一变,所有消费者都重渲染, 哪怕它只用了其中一个字段。 Redux 的 useSelector只在你选的那部分变化时重渲染。这是最大的实际差别。
  • 没有中间件。统一处理异步、日志、 持久化都要自己造。
  • 没有 DevTools。时间旅行、action 记录、 状态 diff 都没有。
ContextRedux
适合主题、当前用户、语言 ——不常变频繁变、多处读写、需要调试追溯
订阅粒度整个 value按 selector
额外依赖
样板代码有(Redux Toolkit 后少很多)

会追问:「现在还用 Redux 吗?」—— 答得诚实一点:纯客户端状态很多项目改用 Zustand / Jotai(更轻);服务端数据用 TanStack Query / SWR(缓存、去重、重试是它们的本职, Redux 做这个是硬凑)。Redux 现在的强项是「复杂的、 有大量交互逻辑的客户端状态 + 要可追溯调试」, 而且一定要用 Redux Toolkit 而不是手写。

In one line — and this is the key sentence: they do not solve the same problem. Context is a delivery mechanism (how a value reaches something deep in the tree); Redux is a state management solution (how state is organised, changed and debugged).

“Can Context replace Redux?” — strictly speaking, Context plus useReducer covers Redux’s basic features, but three things are missing:

  • No fine-grained subscription. When the context changes, every consumer re-renders, even one that only reads a single field. Redux’s useSelector re-renders only when the slice you selected changes. That is the biggest practical difference.
  • No middleware. Handling async, logging and persistence in one place is all yours to build.
  • No DevTools. No time travel, no action log, no state diff.
ContextRedux
Good forTheme, current user, locale — rarely changesChanges often, read and written in many places, needs a debuggable trail
Subscription granularityThe whole valuePer selector
Extra dependencyNoneYes
BoilerplateLittleSome (far less since Redux Toolkit)

Follow-up: “Do people still use Redux?” — answer honestly: plenty of projects moved pure client state to Zustand or Jotai (lighter); server data goes to TanStack Query or SWR (caching, deduping and retries are their day job, and Redux doing it is a stretch). Redux’s remaining strength is complex client state with a lot of interaction logic that you need to be able to trace, and you should always use Redux Toolkit rather than write it by hand.