Advanced React Development

Master advanced React patterns, state management, performance optimization, and testing.

advanced Frontend Frameworks 8 hours

Chapter 13: State Management Alternatives

Chapter 13 of 15

Chapter 13: State Management Alternatives

13.1 Zustand

Zustand is a small, fast, and scalable state management solution.

import create from 'zustand';

const useStore = create((set) => ({
    count: 0,
    increment: () => set((state) => ({ count: state.count + 1 })),
    decrement: () => set((state) => ({ count: state.count - 1 })),
    reset: () => set({ count: 0 })
}));

// Usage
function Counter() {
    const { count, increment, decrement } = useStore();
    return (
        <div>
            <button onClick={decrement}>-</button>
            <span>{count}</span>
            <button onClick={increment}>+</button>
        </div>
    );
}

13.2 Jotai

Jotai uses atomic state management with a bottom-up approach.

import { atom, useAtom } from 'jotai';

const countAtom = atom(0);
const doubleCountAtom = atom((get) => get(countAtom) * 2);

function Counter() {
    const [count, setCount] = useAtom(countAtom);
    const [doubleCount] = useAtom(doubleCountAtom);
    
    return (
        <div>
            <p>Count: {count}</p>
            <p>Double: {doubleCount}</p>
            <button onClick={() => setCount(c => c + 1)}>Increment</button>
        </div>
    );
}

13.3 Recoil

Recoil provides a data-flow graph for state management.

import { atom, selector, useRecoilState, useRecoilValue } from 'recoil';

const countState = atom({
    key: 'countState',
    default: 0
});

const doubleCountState = selector({
    key: 'doubleCountState',
    get: ({ get }) => get(countState) * 2
});

function Counter() {
    const [count, setCount] = useRecoilState(countState);
    const doubleCount = useRecoilValue(doubleCountState);
    
    return (
        <div>
            <p>Count: {count}</p>
            <p>Double: {doubleCount}</p>
            <button onClick={() => setCount(c => c + 1)}>Increment</button>
        </div>
    );
}

13.4 When to Use Each

  • Redux: Complex state, time-travel debugging, large teams
  • Zustand: Simple state, minimal boilerplate, small to medium apps
  • Jotai: Atomic state, fine-grained updates, component-level state
  • Recoil: Complex derived state, async state, Facebook-scale apps
  • Context API: Simple global state, theme, user preferences