English

Modern React state management has evolved beyond Redux. Let's compare the top alternatives.

Zustand - Simplified State Management

import create from 'zustand';

interface TodoStore {
  todos: Todo[];
  addTodo: (todo: Todo) => void;
  removeTodo: (id: string) => void;
}

const useTodoStore = create<TodoStore>((set) => ({
  todos: [],
  addTodo: (todo) => set((state) => ({
    todos: [...state.todos, todo]
  })),
  removeTodo: (id) => set((state) => ({
    todos: state.todos.filter(t => t.id !== id)
  })),
}));

// Usage in components
function TodoList() {
  const todos = useTodoStore((state) => state.todos);
  const addTodo = useTodoStore((state) => state.addTodo);

  return (
    <div>
      {todos.map(todo => <TodoItem key={todo.id} {...todo} />)}
    </div>
  );
}

Pros:

  • Simple API, minimal boilerplate
  • Built-in DevTools support
  • Excellent performance
  • TypeScript-first

Jotai - Atomic State

import { atom, useAtom } from 'jotai';

// Primitive atoms
const countAtom = atom(0);
const todoListAtom = atom<Todo[]>([]);

// Derived atoms
const completedTodosAtom = atom((get) =>
  get(todoListAtom).filter(t => t.completed)
);

// Async atoms
const userAtom = atom(async () => {
  const response = await fetch('/api/user');
  return response.json();
});

// Usage
function Counter() {
  const [count, setCount] = useAtom(countAtom);
  return (
    <button onClick={() => setCount(c => c + 1)}>
      Count: {count}
    </button>
  );
}

Pros:

  • React-like API (useState-style)
  • Atomic updates
  • Built-in async support
  • Bottom-up approach

Valtio - Proxy-based State

import { proxy, useSnapshot } from 'valtio';

const state = proxy({
  count: 0,
  todos: [],
  addTodo(todo: Todo) {
    state.todos.push(todo);
  },
  increment() {
    state.count++;
  },
});

// Usage
function Counter() {
  const snap = useSnapshot(state);
  return (
    <button onClick={() => state.increment()}>
      Count: {snap.count}
    </button>
  );
}

Pros:

  • Mutable-style updates
  • Automatic re-renders
  • Simple mental model
  • Great for complex nested states

When to Use What?

Use Zustand when:

  • You want a Redux-like pattern without complexity
  • Need global state with selectors
  • Want DevTools integration

Use Jotai when:

  • Building bottom-up with atomic pieces
  • Need fine-grained reactivity
  • Working with async data

Use Valtio when:

  • Prefer mutable-style updates
  • Have deeply nested state
  • Want simplest possible API

All three are excellent choices - pick based on your team's preferences!

0
0
0
0