useReducer

const [state, dispatch] = ...

useReducer Hook

A powerful alternative to useState. It lets you manage complex state logic by separating *how* state updates (reducer) from *when* it updates (dispatch).
Continue

The Mental Model

Think of it as a state machine. You don't update state directly. You send an **Action** to a **Reducer**, which calculates the **New State**.
Continue

The Reducer Function

A pure function that takes the current state and an action, and returns the next state. It's predictable and easy to test.
Continue

Dispatching Actions

To change state, you **dispatch** an action object (usually with a `type`). This signals the reducer to run its logic.
Continue

See it in Action

Try the counter demo. Every click sends an action to the reducer. The reducer decides how usage affects the state.
Continue

1. Define the Reducer

Write a pure function that handles state transitions based on action types.

reducer.ts
// 1. The Reducer Function
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}
Pure Logic

2. Use the Hook

Initialize `useReducer` with your reducer function and initial state. It gives you the current `state` and a `dispatch` function.

Counter.tsx
import { useReducer } from 'react';

function Counter() {
  // 2. Initialize Hook
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      Count: {state.count}
      {/* 3. Dispatch Actions */}
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
    </div>
  );
}
Component Integration

Pro Tip: Action Creators

Instead of dispatching raw objects, use helper functions to keep code clean and typo-free.

actions.ts
// Action Types (Constants)
const ACTION = {
    INCREMENT: 'INCREMENT',
    DECREMENT: 'DECREMENT'
};

// Dispatch like this:
dispatch({ type: ACTION.INCREMENT });
Type Safety
AlgoAnimator: Interactive Data Structures