Zustand & Redux Toolkit

0/3 in this phase0/36 across the roadmap

📖 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

codeTap to expand ⛶
1// --- ZUSTAND EXAMPLE ---
2import { create } from 'zustand'
3
4// 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}))
12
13// 2. Component A: Consuming state
14function CartCount() {
15 // Component only re-renders if items.length changes
16 const count = useCartStore((state) => state.items.length)
17 return <div className="badge">{count}</div>
18}
19
20// 3. Component B: Triggering actions
21function AddToCart({ product }) {
22 const addItem = useCartStore((state) => state.addItem)
23 return (
24 <button onClick={() => addItem(product)}>
25 Add to Cart
26 </button>
27 )
28}
29
30// --- REDUX TOOLKIT EXAMPLE (Slice) ---
31/*
32import { createSlice } from '@reduxjs/toolkit'
33
34export 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 += 1
41 }
42 }
43})
44*/

🏋️ Practice Exercise

  1. Install zustand and build a simple 'Task Board' (Todo) with it.
  2. Implement a 'Persist' middleware with Zustand to keep state in LocalStorage automatically.
  3. Compare the amount of code needed to build a counter in Redux Toolkit vs Zustand.
  4. 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