Zustand & Redux Toolkit
📖 Concept
When Context isn't enough, we turn to external state management libraries.
Redux Toolkit (RTK):
The modern way to use Redux. It removes the boilerplate (actions, constants, switch statements) and includes immer for "mutable" state updates and redux-thunk for async logic.
- Best for: Massive enterprise apps with complex, multi-step workflows.
Zustand: A small, fast, and scalable bear-themed state management library. It uses hooks as its primary API and is much simpler than Redux.
- Why it's popular: No Providers needed, zero boilerplate, and it solves the Context re-render problem by using "selectors".
Key Principle: Selectors
Libraries like Zustand allow you to "select" only the specific piece of state you need.
const name = useStore(state => state.user.name);
If state.user.age changes, this component will not re-render. This is the superpower of state libraries.
💻 Code Example
1// --- ZUSTAND EXAMPLE ---2import { create } from 'zustand'34// 1. Create the store (No Provider needed!)5const useCartStore = create((set) => ({6 items: [],7 addItem: (item) => set((state) => ({8 items: [...state.items, item]9 })),10 clearCart: () => set({ items: [] }),11}))1213// 2. Component A: Consuming state14function CartCount() {15 // Component only re-renders if items.length changes16 const count = useCartStore((state) => state.items.length)17 return <div className="badge">{count}</div>18}1920// 3. Component B: Triggering actions21function AddToCart({ product }) {22 const addItem = useCartStore((state) => state.addItem)23 return (24 <button onClick={() => addItem(product)}>25 Add to Cart26 </button>27 )28}2930// --- REDUX TOOLKIT EXAMPLE (Slice) ---31/*32import { createSlice } from '@reduxjs/toolkit'3334export const counterSlice = createSlice({35 name: 'counter',36 initialState: { value: 0 },37 reducers: {38 increment: (state) => {39 // RTK uses Immer, so you can "mutate" the state!40 state.value += 141 }42 }43})44*/
🏋️ Practice Exercise
- Install
zustandand build a simple 'Task Board' (Todo) with it. - Implement a 'Persist' middleware with Zustand to keep state in LocalStorage automatically.
- Compare the amount of code needed to build a counter in Redux Toolkit vs Zustand.
- Research 'Recoil' or 'Jotai' and explain how 'Atomic State' differs from the single-store approach of Redux/Zustand.
⚠️ Common Mistakes
Over-engineering simple apps by adding Redux/Zustand before they are needed.
Storing 'Server State' (API data) in a global store instead of using TanStack Query.
Not using selectors in Zustand, causing the entire component to re-render on any store change.
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Zustand & Redux Toolkit