惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 【当耐特】
Scott Helme
Scott Helme
Google Online Security Blog
Google Online Security Blog
L
LINUX DO - 最新话题
O
OpenAI News
S
Secure Thoughts
Cisco Talos Blog
Cisco Talos Blog
Forbes - Security
Forbes - Security
V
Visual Studio Blog
有赞技术团队
有赞技术团队
Jina AI
Jina AI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Troy Hunt's Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
Schneier on Security
雷峰网
雷峰网
The Cloudflare Blog
量子位
Last Week in AI
Last Week in AI
T
Tor Project blog
V
Vulnerabilities – Threatpost
C
Cisco Blogs
B
Blog RSS Feed
S
Security @ Cisco Blogs
T
Threat Research - Cisco Blogs
G
GRAHAM CLULEY
MyScale Blog
MyScale Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Schneier on Security
Schneier on Security
Martin Fowler
Martin Fowler
Help Net Security
Help Net Security
J
Java Code Geeks
人人都是产品经理
人人都是产品经理
G
Google Developers Blog
S
Security Affairs
A
Arctic Wolf
T
Tenable Blog
PCI Perspectives
PCI Perspectives
Spread Privacy
Spread Privacy
AI
AI
L
LangChain Blog
Latest news
Latest news
博客园 - 叶小钗
博客园 - Franky
T
Threatpost
MongoDB | Blog
MongoDB | Blog
Hugging Face - Blog
Hugging Face - Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
State management in React: when Redux, Zustand, and Context API actually fit
Amanda Gama · 2026-05-10 · via DEV Community

Every React project hits the same fork around month two. Prop drilling gets old. Someone says "we need state management." The next two days are an opinion war. Redux because it's what we know. Zustand because someone read a blog post. Context because "isn't that built in?"

The mistake isn't picking the wrong tool. It's not noticing that the three you're choosing between solve different problems.

What each one actually is

Quick mental models. Most of the confusion lives there.

Context API is a transport mechanism, not a state library. It lets a value cross the tree without prop drilling. That's it. The "state" that lives in a context is whatever you put in a useState near the provider. When that value's identity changes, every consumer re-renders. No selector layer, no batching, no devtools. It's a wire, not a store.

Redux is a single store with predictable, traceable updates. One reducer, one source of truth, every change goes through the same pipeline so you can replay it. Time travel debugging falls out of the design.

The Redux you remember is probably not the Redux anyone writes today. The action types, the action creators, the reducer switch statements, the connect HOC, the mapStateToProps, the boilerplate that made Redux a punchline: that's old Redux. Redux Toolkit (RTK) is what you'd actually write now. The trauma is real, the boilerplate isn't, and that gap does a lot of unfair work in most "Redux vs X" comparisons.

Zustand is a hook around a store. No provider, no reducer, no actions. You define a store, you read from it with a selector, you call methods on it to update. Closer to "useState that lives outside the component" than to a Flux-style architecture.

The same trivial example in all three, just to feel the gap:

// Context API
const UserContext = createContext<{
  user: User | null
  setUser: (u: User | null) => void
} | null>(null)

function UserProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null)
  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  )
}

const ctx = useContext(UserContext)!
ctx.setUser(next)

Enter fullscreen mode Exit fullscreen mode

// Redux Toolkit
const userSlice = createSlice({
  name: 'user',
  initialState: null as User | null,
  reducers: {
    setUser: (_, action: PayloadAction<User | null>) => action.payload,
  },
})

const store = configureStore({ reducer: { user: userSlice.reducer } })

const user = useSelector((s: RootState) => s.user)
const dispatch = useDispatch()
dispatch(userSlice.actions.setUser(next))

Enter fullscreen mode Exit fullscreen mode

// Zustand
const useUserStore = create<{
  user: User | null
  setUser: (u: User | null) => void
}>((set) => ({
  user: null,
  setUser: (user) => set({ user }),
}))

const user = useUserStore((s) => s.user)
const setUser = useUserStore((s) => s.setUser)

Enter fullscreen mode Exit fullscreen mode

Not a fair fight on its own (Redux earns its weight elsewhere, we'll get there). At the trivial end, though, the boilerplate gap is real.

One honest aside before going further

Before going further: a big chunk of the state you think is client state is actually server state. The user's profile from the API. The list of orders. The dashboard data. None of that is "state your app owns." It's a cache of something the server owns.

TanStack Query (or SWR, or Apollo) handles server state better than any of these three. Caching, revalidation, request deduping, stale-while-revalidate, background refresh, retry: they exist as features there, not in Redux or Zustand. If you're reaching for a state library to hold an array you just fetched, you're reaching for the wrong thing.

The rest of this post is about state your client actually owns: UI state, ephemeral state that spans the app, form draft state, things only your app cares about.

When Context API wins

Values that rarely change but need to cross the tree.

Theme. Locale. Current user (if you're not using a server state library to fetch them). Feature flags. Whether the app is online. The kind of data set once at app start and rarely changes after.

type Theme = 'light' | 'dark'

const ThemeContext = createContext<{
  theme: Theme
  setTheme: (t: Theme) => void
} | null>(null)

function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>('light')
  const value = useMemo(() => ({ theme, setTheme }), [theme])
  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
}

Enter fullscreen mode Exit fullscreen mode

Why Context works here:

  • It's already in React. No bundle cost, no library decision.
  • The value rarely changes, so re-rendering every consumer doesn't bite.
  • You're modeling something that's genuinely local to a part of the tree, not global.

The trap is using Context for state that changes constantly. A form context that updates on every keystroke and re-renders the whole form tree is the bad case everyone hits. People feel the lag, blame React, and reach for memoization instead of recognizing that Context wasn't built for that.

Rough test: if the value updates more than a couple of times per minute, or has more than a few unrelated consumers, Context is going to cost you. Reach for a store.

When Zustand wins

Most apps that aren't huge.

Zustand fits the case where you want a store without the architecture lecture. No provider. No reducer split. Async lives in regular functions on the store, not in middleware. TypeScript inference works without four lines of generic incantations. Selectors mean components only re-render when the slice they care about changes.

type CartState = {
  items: CartItem[]
  addItem: (item: CartItem) => void
  removeItem: (id: string) => void
  checkout: () => Promise<void>
}

const useCartStore = create<CartState>((set, get) => ({
  items: [],
  addItem: (item) => set((s) => ({ items: [...s.items, item] })),
  removeItem: (id) => set((s) => ({ items: s.items.filter((i) => i.id !== id) })),
  checkout: async () => {
    await api.post('/checkout', { items: get().items })
    set({ items: [] })
  },
}))

function CartCount() {
  const count = useCartStore((s) => s.items.length)
  return <span>{count}</span>
}

Enter fullscreen mode Exit fullscreen mode

CartCount re-renders when the count changes. Updating a quantity on an existing item without changing length doesn't re-render it. That selector behavior does real work.

Async is the part where Zustand quietly wins. No debate over thunks versus sagas, no extra dependency. The store action is an async function. It awaits, it sets, it's done. That's the whole pattern.

The catch: Zustand stays small and ergonomic by not giving you much structure. At very large team sizes, with many engineers touching the same store, you start writing your own conventions for splitting stores, organizing actions, handling communication between stores. By the time you've done that for a while, you've reinvented a worse Redux. That's not a reason to skip Zustand. It's a reason to notice the moment when the lack of structure stops being a feature.

When Redux (RTK) wins

Larger teams, larger surface area, complex async, and the case where DevTools earn their keep.

The honest sell for Redux today is the ecosystem. Redux DevTools is still the best experience for debugging state in any framework. Time-travel works. Action history is a real thing you can scroll back through. RTK Query, if you go with it instead of TanStack Query, is genuinely solid for server state and integrates with the rest of the store. Listener middleware (the new alternative to sagas) covers most of the cases that used to need extra libraries for side effects.

type Status = 'idle' | 'loading' | 'error'

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [] as CartItem[], status: 'idle' as Status },
  reducers: {
    itemAdded: (state, action: PayloadAction<CartItem>) => {
      state.items.push(action.payload)
    },
    itemRemoved: (state, action: PayloadAction<string>) => {
      state.items = state.items.filter((i) => i.id !== action.payload)
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(checkout.pending, (s) => { s.status = 'loading' })
      .addCase(checkout.fulfilled, (s) => { s.status = 'idle'; s.items = [] })
      .addCase(checkout.rejected, (s) => { s.status = 'error' })
  },
})

const checkout = createAsyncThunk('cart/checkout', async (_, { getState }) => {
  const items = (getState() as RootState).cart.items
  await api.post('/checkout', { items })
})

Enter fullscreen mode Exit fullscreen mode

Noticeably more file than the Zustand version. Some of the noise is genuine: explicit action types are what make time travel possible, and extraReducers is what lets you express loading, success, and error in one place. Some of it is just RTK being thorough about TypeScript.

When that overhead pays for itself:

  • More than a handful of engineers touch the same state. The structure stops being a tax and starts being a contract.
  • You depend on DevTools for debugging. During incident response, replaying a sequence of actions to reproduce a bug is a superpower.
  • You have complex middleware needs: throttling, debouncing, coordination between stores, optimistic updates with conflict resolution. The listener middleware story is good.
  • You've already committed to RTK Query for server state. Mixing it with Zustand isn't impossible, but now you're running two state systems.

When it doesn't: small to mid apps, solo dev or small team, no exotic patterns for side effects. RTK isn't bad there. It's just paying for capabilities you won't use.

The dimensions you feel later

The stuff that doesn't show up in a tutorial but matters in month six.

DevTools. Redux: best in class. Zustand: middleware that gives you the same Redux DevTools, basic but works. Context: nothing, you're back to console.log.

Async and side effects. Redux: thunks for simple, listener middleware for complex, RTK Query for server. Zustand: async functions in the store, that's it. Context: not its job, bring your own.

TypeScript. Zustand: clean inference, minimal ceremony. RTK: good but verbose, PayloadAction and RootState show up everywhere. Context: fine for static types, awkward when you want a non-null guarantee inside consumers.

Performance. Zustand and Redux both subscribe through selectors, so components only re-render when their slice changes. Context re-renders every consumer on every value change unless you split providers or memoize aggressively. For state that changes constantly, Context will be the bottleneck before any of the others.

Testing. Zustand stores are plain functions, you can call them in a test without a renderer. RTK reducers are pure, also easy to test. Context-based state usually means rendering a tree, which is heavier and slower.

What I reach for now

In practice, I default to two options: Zustand, or nothing.

For small apps, nothing usually means Context for the few values that need to cross the tree (auth, theme, locale) and useState everywhere else. That covers more apps than people think. The "you need state management" reflex kicks in earlier than the actual need does.

For anything bigger, Zustand. The boilerplate cost is low enough that I'll reach for it the moment a value needs to be touched from two unrelated parts of the tree. Selectors handle re-renders, async fits in the store, TypeScript stays out of the way. I don't reach for Redux on new projects, not because RTK is bad, but because I keep finding I don't need what it gives me.

I'd reach for Redux if I were joining a team that already uses it (don't fight that battle), or starting something where DevTools and a strict structure across a large team are the actual problem to solve. Those are real cases. They're just not most cases.

The decision isn't "which one is best." It's "which problem do I actually have." Context if you have prop drilling and not much else. Zustand if you have shared client state and want a store without ceremony. Redux if you have a team and a surface area large enough to make the structure pay rent.

Pick the smallest one that fits, and trade up only when you feel the seams.