Global State (Redux vs Zustand)
Definition
Global State Management libraries solve the problem of sharing state across massive, complex applications where the Context API becomes too slow or unwieldy. Redux is the traditional heavyweight, while Zustand and Recoil are modern, lightweight alternatives.
Explain Like I'm New
Imagine a library. Context API is like everyone shouting book requests across the room; it works for a small room, but gets chaotic fast. Redux is a strict, heavily bureaucratic library: you must fill out 3 forms (Actions, Reducers, Dispatchers) just to check out a book. Zustand is like an open, modern library: there's a central desk with a very simple system to check out books immediately.
Real World Example
In a social media app, your 'Current User Profile', 'Unread Notifications Count', and 'Theme' need to be accessed by almost every component on screen. Using a global store prevents you from passing these via props down 20 levels.
Common Use Cases
- •Managing highly complex, frequently updating state
- •Time-travel debugging (undo/redo functionality easily built with Redux)
- •Decoupling business logic from UI components
Interactive Example
// --- A Simple Zustand Implementation --- // npm install zustand /* import { create } from 'zustand' // 1. Create the global store const useBearStore = create((set) => ({ bears: 0, increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), removeAllBears: () => set({ bears: 0 }), })) // 2. Consume it anywhere in your app (No Providers needed!) function BearCounter() { // Selecting only the specific data we need prevents unnecessary re-renders const bears = useBearStore((state) => state.bears) return <h1>{bears} around here ...</h1> } function Controls() { const increasePopulation = useBearStore((state) => state.increasePopulation) return <button onClick={increasePopulation}>one up</button> } */ console.log("Zustand provides a tiny, unopinionated global state solution compared to Redux's strict architecture.");
Interview Questions
basic
- Why use Redux or Zustand instead of just Context API?
- What are the three core principles of Redux?
intermediate
- What is a 'Store' in global state?
- How does Zustand differ from Redux?
advanced
- What is Redux Toolkit (RTK) and why was it created?
- What are 'selectors' and why are they important for performance?
trick
- Do you HAVE to use a state management library in React?