15. Introduction to State Management Libraries (Redux & Zustand)
Why Use State Management?
As apps grow, sharing state across multiple components gets messy. Passing props through many levels (prop drilling) makes components harder to manage and debug. State management tools help make data flow predictable and centralized.
- Avoid prop drilling
- Share state between distant components
- Organize business logic better
- Make state predictable and easier to debug
What Is Redux?
Redux is a popular state management library that uses a strict data flow: actions → reducer → store → UI. It's great for large apps that need structure and predictability.
import { createStore } from 'redux'
const initialState = { count: 0 }
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 }
case 'DECREMENT':
return { count: state.count - 1 }
default:
return state
}
}
export const store = createStore(counterReducer)Redux adds structure but can feel heavy because it uses actions and reducers.
What Is Zustand?
Zustand is a lightweight alternative to Redux. It has a simple API and doesn’t need reducers or actions. It’s perfect for small to medium-sized apps.
import { create } from 'zustand'
export const useStore = create(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
decrement: () => set(state => ({ count: state.count - 1 }))
}))Redux vs Zustand
| Feature | Redux | Zustand |
|---|---|---|
| Boilerplate | High | Low |
| Learning Curve | Medium | Easy |
| Best For | Large apps | Small–medium apps |
| DevTools Support | Yes | Yes |
| Performance | Good | Excellent |
Both are great tools, but Zustand is easier to start with and perfect for most projects.
Mini Project Step
Add a global state store to your project using Zustand. We'll manage a simple app theme (light/dark mode) globally so every component can access it.
// src/store/themeStore.js
import { create } from 'zustand'
export const useThemeStore = create(set => ({
theme: 'light',
toggleTheme: () => set(state => ({ theme: state.theme === 'light' ? 'dark' : 'light' }))
}))In the next lesson, we’ll connect this store to our components and start using global state in the UI.