← Back to Articles         
 useReducer - React Hook

useReducer - React Hook

Published on 15 Nov 2026 25 min read React
React Fundamentals

1. What is useReducer?

useReducer is a React Hook used to manage state in a component.

It is an alternative to useState, especially when:

  • State has multiple related values.
  • State changes depend on different types of actions.
  • State update logic is becoming complicated.
  • Many event handlers are changing the same state.
  • You want to keep state-changing logic in one place.

The basic idea is:

User Action
    ↓
dispatch(action)
    ↓
reducer(state, action)
    ↓
new state
    ↓
React re-renders component

For example, instead of writing several setState() calls:

setCount(count + 1);
setCount(count - 1);
setCount(0);

you can describe what happened:

dispatch({ type: "increment" });
dispatch({ type: "decrement" });
dispatch({ type: "reset" });

The reducer decides how the state should change.


2. Why do we need useReducer?

For simple state, useState is usually easier.

const [count, setCount] = useState(0);

const increment = () => {
  setCount(count + 1);
};

But imagine a form with:

name
email
password
loading
error
success
validation

and many different actions can modify these values.

The component can become difficult to manage:

setName(...);
setEmail(...);
setPassword(...);
setLoading(...);
setError(...);
setSuccess(...);

With useReducer, related state changes can be centralized:

Component
   │
   │ dispatch()
   ↓
Reducer
   │
   │ decides state change
   ↓
New State
   │
   ↓
Component re-renders

This makes complex state management more predictable.


3. useReducer vs useState

Both manage component state.

useState useReducer
Simple state Complex state
Direct state updates Action-based updates
Easy to learn Slightly more code
Good for isolated values Good for related state
Logic often stays in handlers Logic centralized in reducer
setState() dispatch()

Use useState

const [name, setName] = useState("");

For simple state, this is excellent.

Use useReducer

const [state, dispatch] = useReducer(reducer, initialState);

When several state transitions are involved, useReducer becomes more useful.


4. The basic structure of useReducer

The most common form is:

const [state, dispatch] = useReducer(reducer, initialState);

There are three important parts.

1. State

state

Contains the current state.

2. Dispatch

dispatch(...)

Used to tell the reducer that something happened.

3. Reducer

reducer(state, action)

Contains the logic for changing the state.


5. How does useReducer work?

Consider a counter.

import { useReducer } from "react";

function reducer(state: number, action: { type: string }) {
  if (action.type === "increment") {
    return state + 1;
  }

  if (action.type === "decrement") {
    return state - 1;
  }

  if (action.type === "reset") {
    return 0;
  }

  return state;
}

export default function Counter() {
  const [count, dispatch] = useReducer(reducer, 0);

  return (
    <div>
      <h2>{count}</h2>

      <button onClick={() => dispatch({ type: "increment" })}>
        +
      </button>

      <button onClick={() => dispatch({ type: "decrement" })}>
        -
      </button>

      <button onClick={() => dispatch({ type: "reset" })}>
        Reset
      </button>
    </div>
  );
}

Data flow

When the user clicks +:

dispatch({ type: "increment" });

React sends this action to the reducer:

reducer(currentState, action)

The reducer sees:

action.type === "increment"

and returns:

state + 1

React stores the new state and renders the component again.

count = 5

User clicks +
      ↓
dispatch({ type: "increment" })
      ↓
reducer(5, { type: "increment" })
      ↓
returns 6
      ↓
React updates state
      ↓
Component re-renders
      ↓
count displays 6

6. What is a reducer?

A reducer is simply a function that determines the next state based on the current state and an action.

Conceptually:

function reducer(state, action) {
  // decide what the next state should be

  return newState;
}

Its general form is:

function reducer(state, action) {
  switch (action.type) {
    case "someAction":
      return newState;

    default:
      return state;
  }
}

A reducer does not directly update the existing state.

Instead, it returns the new state.


7. What is an action?

An action is an object describing what happened.

Example:

dispatch({ type: "increment" });

The action is:

{
  type: "increment"
}

Actions can also carry data.

dispatch({
  type: "add",
  payload: 10
});

The reducer can access that data:

function reducer(state, action) {
  if (action.type === "add") {
    return state + action.payload;
  }

  return state;
}

Now:

dispatch({
  type: "add",
  payload: 10
});

means:

Current state = 20
       ↓
action = add 10
       ↓
New state = 30

8. Action type and payload

A common pattern is:

{
  type: "ADD_TODO",
  payload: {
    id: 1,
    text: "Learn React"
  }
}

type

Describes what happened.

type: "ADD_TODO"

payload

Contains additional information required to perform the action.

payload: {
  id: 1,
  text: "Learn React"
}

This gives you a clean separation:

type    → What happened?
payload → What data is required?

9. Basic counter using switch

For real applications, switch is commonly used because it makes multiple actions easy to read.

import { useReducer } from "react";

type Action =
  | { type: "increment" }
  | { type: "decrement" }
  | { type: "reset" };

function reducer(state: number, action: Action) {
  switch (action.type) {
    case "increment":
      return state + 1;

    case "decrement":
      return state - 1;

    case "reset":
      return 0;

    default:
      return state;
  }
}

export default function Counter() {
  const [count, dispatch] = useReducer(reducer, 0);

  return (
    <>
      <h2>Count: {count}</h2>

      <button onClick={() => dispatch({ type: "increment" })}>
        Increment
      </button>

      <button onClick={() => dispatch({ type: "decrement" })}>
        Decrement
      </button>

      <button onClick={() => dispatch({ type: "reset" })}>
        Reset
      </button>
    </>
  );
}

Expected behavior:

Initial: 0

Increment → 1
Increment → 2
Decrement → 1
Reset     → 0

10. useReducer with an object state

useReducer becomes more useful when state contains multiple related properties.

For example:

type State = {
  name: string;
  age: number;
  isAdmin: boolean;
};

Initial state:

const initialState: State = {
  name: "Syed",
  age: 48,
  isAdmin: false
};

Reducer:

function reducer(state: State, action: any): State {
  switch (action.type) {
    case "changeName":
      return {
        ...state,
        name: action.payload
      };

    case "increaseAge":
      return {
        ...state,
        age: state.age + 1
      };

    case "toggleAdmin":
      return {
        ...state,
        isAdmin: !state.isAdmin
      };

    default:
      return state;
  }
}

The important concept is:

return {
  ...state,
  name: action.payload
};

You create a new state object while preserving the other properties.


11. Why is immutability important?

This is incorrect:

state.count++;
return state;

You are modifying the existing state object.

Instead:

return {
  ...state,
  count: state.count + 1
};

You create a new object.

Think of it as:

Old State
   ↓
Do not modify
   ↓
Create New State
   ↓
React detects state change

This is one of the most important rules when using reducers.


12. useReducer with payload

Suppose you want to change a username.

dispatch({
  type: "setName",
  payload: "Syed"
});

Reducer:

function reducer(state, action) {
  switch (action.type) {
    case "setName":
      return {
        ...state,
        name: action.payload
      };

    default:
      return state;
  }
}

The flow is:

Input
 ↓
dispatch()
 ↓
action
 ↓
reducer()
 ↓
new state
 ↓
re-render

13. Real-world example: Login form

useReducer is very useful when a component has several related states.

For example:

username
password
loading
error
success

State

type State = {
  username: string;
  password: string;
  loading: boolean;
  error: string;
  success: boolean;
};

Initial state:

const initialState: State = {
  username: "",
  password: "",
  loading: false,
  error: "",
  success: false
};

Reducer:

type Action =
  | { type: "setUsername"; payload: string }
  | { type: "setPassword"; payload: string }
  | { type: "loginStart" }
  | { type: "loginSuccess" }
  | { type: "loginError"; payload: string };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "setUsername":
      return {
        ...state,
        username: action.payload
      };

    case "setPassword":
      return {
        ...state,
        password: action.payload
      };

    case "loginStart":
      return {
        ...state,
        loading: true,
        error: ""
      };

    case "loginSuccess":
      return {
        ...state,
        loading: false,
        success: true
      };

    case "loginError":
      return {
        ...state,
        loading: false,
        error: action.payload
      };

    default:
      return state;
  }
}

Component:

const [state, dispatch] = useReducer(reducer, initialState);

Username:

<input
  value={state.username}
  onChange={(e) =>
    dispatch({
      type: "setUsername",
      payload: e.target.value
    })
  }
/>

Login:

async function login() {
  dispatch({ type: "loginStart" });

  try {
    // API call

    dispatch({ type: "loginSuccess" });
  } catch {
    dispatch({
      type: "loginError",
      payload: "Invalid username or password"
    });
  }
}

The state transition becomes easy to understand:

User enters username
       ↓
setUsername
       ↓
username updated

User clicks Login
       ↓
loginStart
       ↓
loading = true

API succeeds
       ↓
loginSuccess
       ↓
loading = false
success = true

This is much easier to manage when the number of states and transitions grows.


14. Real-world example: Todo application

A todo application is a classic useReducer example.

State:

type Todo = {
  id: number;
  text: string;
  completed: boolean;
};

type State = {
  todos: Todo[];
};

Actions:

ADD_TODO
TOGGLE_TODO
DELETE_TODO
CLEAR_COMPLETED

Reducer:

function reducer(state: State, action: any): State {
  switch (action.type) {
    case "ADD_TODO":
      return {
        ...state,
        todos: [
          ...state.todos,
          {
            id: Date.now(),
            text: action.payload,
            completed: false
          }
        ]
      };

    case "TOGGLE_TODO":
      return {
        ...state,
        todos: state.todos.map(todo =>
          todo.id === action.payload
            ? {
                ...todo,
                completed: !todo.completed
              }
            : todo
        )
      };

    case "DELETE_TODO":
      return {
        ...state,
        todos: state.todos.filter(
          todo => todo.id !== action.payload
        )
      };

    case "CLEAR_COMPLETED":
      return {
        ...state,
        todos: state.todos.filter(todo => !todo.completed)
      };

    default:
      return state;
  }
}

Now the component can simply dispatch actions:

dispatch({
  type: "ADD_TODO",
  payload: "Learn useReducer"
});

Toggle:

dispatch({
  type: "TOGGLE_TODO",
  payload: todo.id
});

Delete:

dispatch({
  type: "DELETE_TODO",
  payload: todo.id
});

The component doesn't need to know all the state-changing logic.

The reducer owns that logic.


15. useReducer for a shopping cart

Another very practical example is a shopping cart.

State:

type CartItem = {
  id: number;
  name: string;
  price: number;
  quantity: number;
};

type State = {
  items: CartItem[];
};

Actions might be:

ADD_ITEM
REMOVE_ITEM
INCREASE_QUANTITY
DECREASE_QUANTITY
CLEAR_CART

For example:

dispatch({
  type: "ADD_ITEM",
  payload: product
});

Increase quantity:

dispatch({
  type: "INCREASE_QUANTITY",
  payload: productId
});

Remove:

dispatch({
  type: "REMOVE_ITEM",
  payload: productId
});

This is a good example of why reducers are useful.

A shopping cart has many possible state transitions.

                    ┌── ADD_ITEM
                    ├── REMOVE_ITEM
User interaction ───┼── INCREASE_QUANTITY
                    ├── DECREASE_QUANTITY
                    └── CLEAR_CART
                           ↓
                       Reducer
                           ↓
                      New Cart State

16. useReducer for API state

A common pattern is managing API request states.

Instead of:

const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
const [error, setError] = useState("");

you can combine them:

type State = {
  loading: boolean;
  data: User[];
  error: string | null;
};

Typical actions:

FETCH_START
FETCH_SUCCESS
FETCH_ERROR

Reducer:

function reducer(state: State, action: any): State {
  switch (action.type) {
    case "FETCH_START":
      return {
        loading: true,
        data: [],
        error: null
      };

    case "FETCH_SUCCESS":
      return {
        loading: false,
        data: action.payload,
        error: null
      };

    case "FETCH_ERROR":
      return {
        loading: false,
        data: [],
        error: action.payload
      };

    default:
      return state;
  }
}

Then:

dispatch({ type: "FETCH_START" });

After successful API call:

dispatch({
  type: "FETCH_SUCCESS",
  payload: users
});

After failure:

dispatch({
  type: "FETCH_ERROR",
  payload: "Unable to load users"
});

This creates a very clear state machine:

             FETCH_START
                  ↓
              Loading
             /      \
            /        \
           ↓          ↓
 FETCH_SUCCESS     FETCH_ERROR
      ↓                 ↓
   Success             Error

17. useReducer with useEffect

useReducer and useEffect are commonly used together for API operations.

const [state, dispatch] = useReducer(reducer, initialState);

useEffect(() => {
  async function loadUsers() {
    dispatch({ type: "FETCH_START" });

    try {
      const response = await fetch("/api/users");
      const users = await response.json();

      dispatch({
        type: "FETCH_SUCCESS",
        payload: users
      });
    } catch (error) {
      dispatch({
        type: "FETCH_ERROR",
        payload: "Failed to load users"
      });
    }
  }

  loadUsers();
}, []);

Here:

  • useEffect performs the side effect.
  • API response determines what action to dispatch.
  • Reducer changes the state.
  • React re-renders.

Important distinction:

useEffect
    ↓
Performs side effect

useReducer
    ↓
Manages state transitions

The reducer itself should not perform the API call.


18. Reducers should be pure

A reducer should be a pure function.

This means it should generally:

  • use the provided state
  • inspect the action
  • calculate the next state
  • return the next state

For example:

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return {
        count: state.count + 1
      };

    default:
      return state;
  }
}

Avoid doing things such as:

fetch("/api/users");

inside the reducer.

Also avoid:

localStorage.setItem("count", "10");

inside the reducer.

These are side effects.

Better:

useEffect / event handler
       ↓
side effect
       ↓
dispatch()
       ↓
reducer
       ↓
new state

19. Lazy initialization

useReducer supports a third argument for initialization.

useReducer(reducer, initialArg, init);

For example:

function init(initialCount: number) {
  return {
    count: initialCount
  };
}

const [state, dispatch] = useReducer(
  reducer,
  10,
  init
);

The initialization function runs to create the initial state.

This can be useful when initial state needs some calculation.

For example:

function init() {
  const saved = localStorage.getItem("count");

  return {
    count: saved ? Number(saved) : 0
  };
}

Then:

const [state, dispatch] = useReducer(
  reducer,
  undefined,
  init
);

Conceptually:

Component starts
      ↓
init()
      ↓
Initial state
      ↓
useReducer

This is useful when initializing state is more complex than simply providing an object.


20. Resetting state

A reducer can easily support reset functionality.

const initialState = {
  name: "",
  email: "",
  password: ""
};

Reducer:

function reducer(state, action) {
  switch (action.type) {
    case "reset":
      return initialState;

    default:
      return state;
  }
}

Then:

dispatch({ type: "reset" });

Everything returns to the initial state.

This is particularly useful for:

  • forms
  • filters
  • search screens
  • shopping carts
  • multi-step forms

21. Multiple related state values

One major advantage of useReducer is grouping related state.

For example, a form:

const [state, dispatch] = useReducer(reducer, {
  name: "",
  email: "",
  password: "",
  loading: false,
  error: null
});

Instead of several independent state variables:

const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);

Neither approach is automatically better.

The question is:

Are these pieces of state logically related?

If yes, useReducer can be a good choice.


22. useReducer with Context API

This is one of the most important real-world patterns.

useReducer manages the state.

Context shares that state across components.

For example:

                 Context
                   │
          ┌────────┴────────┐
          │                 │
       Header             Product
          │                 │
          └───────┬─────────┘
                  │
             dispatch()
                  ↓
              Reducer
                  ↓
             New State

This is commonly used for:

  • authentication
  • shopping cart
  • theme
  • application settings
  • user preferences

Example:

const CartContext = createContext(null);

Provider:

function CartProvider({ children }) {
  const [state, dispatch] = useReducer(
    cartReducer,
    initialState
  );

  return (
    <CartContext.Provider value={{ state, dispatch }}>
      {children}
    </CartContext.Provider>
  );
}

A child component can then dispatch:

const { dispatch } = useContext(CartContext);

dispatch({
  type: "ADD_ITEM",
  payload: product
});

This is a powerful combination:

useReducer
    ↓
State management

Context API
    ↓
State sharing

23. useReducer + Context for authentication

A typical application might have:

user
isAuthenticated
loading
error

Actions:

LOGIN
LOGOUT
LOGIN_SUCCESS
LOGIN_ERROR

Then:

dispatch({
  type: "LOGIN_SUCCESS",
  payload: user
});

Any component consuming the context can access the authentication state.

For example:

App
 │
 ├── Header
 │     └── Logout
 │
 ├── Dashboard
 │
 └── Profile

All of them can share the same reducer-managed authentication state.

This is often cleaner than passing authentication state through many levels of props.


24. useReducer with useMemo

You may sometimes see:

const value = useMemo(
  () => ({ state, dispatch }),
  [state]
);

This is mainly useful when providing reducer state through Context and you want to control unnecessary object recreation.

For example:

const value = useMemo(
  () => ({ state, dispatch }),
  [state]
);

Then:

<Context.Provider value={value}>

However, don't add useMemo automatically everywhere.

Use it when there is a real performance reason.


25. dispatch does not directly change state

This is an important concept.

When you write:

dispatch({
  type: "increment"
});

you are not directly changing state.

You are sending an action.

React then runs the reducer:

dispatch(action)
      ↓
reducer(currentState, action)
      ↓
newState
      ↓
React re-render

Think of dispatch() as saying:

"This event happened."

The reducer decides:

"Given that event, this is what the new state should be."


26. Actions describe events

Good actions usually describe what happened, rather than directly describing how to change the state.

Good:

dispatch({
  type: "ITEM_ADDED",
  payload: product
});

Less desirable:

dispatch({
  type: "SET_ITEMS",
  payload: newItems
});

Both can work, but event-based actions often make complex reducers easier to understand.

For example:

USER_LOGGED_IN
ITEM_ADDED
ITEM_REMOVED
FORM_SUBMITTED
PAYMENT_SUCCESS
PAYMENT_FAILED

These describe application events.


27. useReducer and derived data

Suppose the state contains:

{
  items: [...]
}

You don't necessarily need another state variable for:

totalItems

You can calculate it:

const totalItems = state.items.length;

Similarly:

const totalPrice = state.items.reduce(
  (total, item) => total + item.price * item.quantity,
  0
);

Avoid storing data that can be calculated from existing state unless there is a good reason.


28. Complex state transitions

This is where useReducer really becomes valuable.

Imagine an order process:

idle
 ↓
processing
 ↓
payment_success
 ↓
order_confirmed

Or:

idle
 ↓
processing
 ├── success
 └── failure

A reducer makes these transitions explicit:

switch (action.type) {
  case "START_PAYMENT":
    return {
      ...state,
      status: "processing"
    };

  case "PAYMENT_SUCCESS":
    return {
      ...state,
      status: "success"
    };

  case "PAYMENT_FAILED":
    return {
      ...state,
      status: "failed"
    };

  default:
    return state;
}

This is essentially a small state machine.


29. useReducer with a state machine mindset

For complex applications, think in terms of:

Current State + Event = Next State

For example:

LoggedOut + LOGIN
       ↓
LoggingIn

LoggingIn + LOGIN_SUCCESS
       ↓
LoggedIn

LoggingIn + LOGIN_FAILED
       ↓
LoggedOut

This mental model makes reducers much easier to design.


30. TypeScript: strongly typed actions

TypeScript is particularly useful with reducers.

Instead of:

action: any

define an action union.

type Action =
  | { type: "increment" }
  | { type: "decrement" }
  | { type: "reset" }
  | { type: "set"; payload: number };

Then:

function reducer(
  state: number,
  action: Action
): number {
  switch (action.type) {
    case "increment":
      return state + 1;

    case "decrement":
      return state - 1;

    case "reset":
      return 0;

    case "set":
      return action.payload;

    default:
      return state;
  }
}

Now TypeScript knows which actions are allowed.

This prevents mistakes such as:

dispatch({
  type: "somethingThatDoesNotExist"
});

31. TypeScript: typed state

You can also define the state separately.

type State = {
  count: number;
  loading: boolean;
};

Then:

function reducer(
  state: State,
  action: Action
): State {
  // ...
}

This gives you strong type checking for both:

State
 +
Action

32. TypeScript: discriminated unions

This is a very important TypeScript pattern.

type Action =
  | {
      type: "SET_NAME";
      payload: string;
    }
  | {
      type: "SET_AGE";
      payload: number;
    }
  | {
      type: "RESET";
    };

Now TypeScript understands:

case "SET_NAME":

means:

action.payload

must be a string.

And:

case "SET_AGE":

means:

action.payload

must be a number.

This is much safer than:

action: any

33. TypeScript: complete example

import { useReducer } from "react";

type State = {
  count: number;
};

type Action =
  | { type: "increment" }
  | { type: "decrement" }
  | { type: "add"; payload: number }
  | { type: "reset" };

const initialState: State = {
  count: 0
};

function reducer(
  state: State,
  action: Action
): State {
  switch (action.type) {
    case "increment":
      return {
        ...state,
        count: state.count + 1
      };

    case "decrement":
      return {
        ...state,
        count: state.count - 1
      };

    case "add":
      return {
        ...state,
        count: state.count + action.payload
      };

    case "reset":
      return initialState;

    default:
      return state;
  }
}

export default function Counter() {
  const [state, dispatch] = useReducer(
    reducer,
    initialState
  );

  return (
    <div>
      <h2>Count: {state.count}</h2>

      <button
        onClick={() =>
          dispatch({ type: "increment" })
        }
      >
        +
      </button>

      <button
        onClick={() =>
          dispatch({ type: "decrement" })
        }
      >
        -
      </button>

      <button
        onClick={() =>
          dispatch({
            type: "add",
            payload: 10
          })
        }
      >
        Add 10
      </button>

      <button
        onClick={() =>
          dispatch({ type: "reset" })
        }
      >
        Reset
      </button>
    </div>
  );
}

This is a good production-style basic reducer pattern.


34. Common mistake: mutating state

Incorrect:

state.items.push(newItem);

return state;

Correct:

return {
  ...state,
  items: [...state.items, newItem]
};

For an object:

return {
  ...state,
  user: {
    ...state.user,
    name: "Syed"
  }
};

For an array:

return {
  ...state,
  items: state.items.filter(item => item.id !== id)
};

35. Common mistake: forgetting return

Incorrect:

case "increment":
  state.count + 1;

The reducer must return the new state:

case "increment":
  return {
    ...state,
    count: state.count + 1
  };

36. Common mistake: changing the wrong state

Suppose:

state.user.name

needs to change.

Don't do:

state.user.name = "Syed";
return state;

Instead:

return {
  ...state,
  user: {
    ...state.user,
    name: "Syed"
  }
};

You need to preserve immutability at each affected object level.


37. Common mistake: putting API calls inside reducer

Don't do:

function reducer(state, action) {
  fetch("/api/users");

  return state;
}

Reducers should calculate state.

Instead:

async function loadUsers() {
  dispatch({ type: "FETCH_START" });

  const response = await fetch("/api/users");

  const users = await response.json();

  dispatch({
    type: "FETCH_SUCCESS",
    payload: users
  });
}

38. Common mistake: using useReducer for everything

You don't need:

useReducer

for:

const [isOpen, setIsOpen] = useState(false);

That would add unnecessary complexity.

Simple state should usually remain simple.


39. Common mistake: creating an enormous reducer

Avoid putting unrelated application features into one reducer:

User
Cart
Products
Notifications
Theme
Settings
Orders
Payments

all inside one giant reducer.

Instead, split state logically:

AuthReducer
CartReducer
ProductReducer
SettingsReducer

And if global sharing is required, combine them through an appropriate architecture.


40. useReducer vs Redux

They are related concepts but are not the same thing.

useReducer

React component
     ↓
useReducer
     ↓
Local component state

It is built into React.

Redux

React application
        ↓
Redux store
        ↓
Global state

Redux provides a broader application state-management architecture.

A useful way to remember:

useReducer is a React Hook for reducer-based state management.

Redux is a separate state-management library/ecosystem that also uses reducer concepts.

You don't need Redux just because you understand reducers.


41. useReducer vs Context API

These solve different problems.

useReducer

Answers:

How should my state change?

Context API

Answers:

How can components access shared data without passing props through every level?

Together:

useReducer
   ↓
Manages state

Context
   ↓
Shares state

This combination is very common for medium-sized React applications.


42. useReducer vs useState

A useful practical rule:

Prefer useState when

isOpen
name
email
count
selectedTab

are simple and mostly independent.

Consider useReducer when

form state
shopping cart
authentication state
API state
multi-step workflow
complex UI state

has many related transitions.


43. When should you use useReducer?

Use it when:

1. State has multiple related values

{
  data,
  loading,
  error
}

2. Many actions modify the same state

ADD
UPDATE
DELETE
RESET

3. State transition logic is complex

idle → loading → success/error

4. Multiple event handlers contain similar state logic

A reducer can centralize that logic.

5. You want predictable state transitions

Actions clearly describe what happened.


44. When should you NOT use useReducer?

Avoid it when the state is extremely simple.

For example:

const [isVisible, setIsVisible] = useState(false);

There is little benefit in writing:

dispatch({
  type: "TOGGLE_VISIBILITY"
});

For simple state, useState is clearer.


45. Performance considerations

useReducer itself is not automatically a performance optimization.

It primarily improves state organization and predictability.

If a reducer-managed state changes:

state changes
      ↓
component re-renders

If the state is provided through Context, components consuming that Context may also re-render when the Context value changes.

For performance-sensitive applications, consider:

  • splitting Contexts
  • keeping state local where possible
  • memoizing expensive calculations
  • useMemo
  • useCallback
  • React.memo
  • avoiding unnecessarily large shared state

46. Reducer organization

For a small component:

function reducer(state, action) {
  ...
}

is perfectly fine.

For larger components, you can move it into another file:

src/
 ├── components/
 │    └── Todo.tsx
 │
 └── reducers/
      └── todoReducer.ts

For example:

// todoReducer.ts

export function todoReducer(state, action) {
  ...
}

Then:

import { todoReducer } from "./todoReducer";

This keeps UI and state-transition logic separated.


47. Reducer testing

One advantage of reducers is that they are easy to test because they are pure functions.

You can conceptually test:

const state = {
  count: 5
};

const newState = reducer(
  state,
  { type: "increment" }
);

Expected:

{
  count: 6
}

You don't necessarily need to render a React component to test this logic.

This is useful in larger applications.


48. Reducer as a state transition function

The most important mental model is:

State + Action
      ↓
   Reducer
      ↓
New State

For example:

State:
count = 10

Action:
{ type: "increment" }

Reducer:
10 + 1

New State:
count = 11

Another example:

State:
cart = [A, B]

Action:
REMOVE_ITEM
payload = B

Reducer:
remove B

New State:
cart = [A]

49. Complete real-world example: Todo app architecture

A clean Todo architecture might look like:

Todo Component
      │
      │ dispatch()
      ↓
Todo Reducer
      │
      │ returns new state
      ↓
Todo State
      │
      ↓
React re-render

Actions:

ADD_TODO
TOGGLE_TODO
DELETE_TODO
CLEAR_COMPLETED
RESET

This provides a predictable model for the entire Todo component.

As the application grows, you can combine it with Context:

                    TodoContext
                        │
               ┌────────┴────────┐
               │                 │
             TodoList         TodoForm
               │                 │
               └────────┬────────┘
                        ↓
                    dispatch
                        ↓
                   todoReducer
                        ↓
                    new state

50. Important React behavior

When you call:

dispatch(action);

React schedules a state update.

You should not expect the state variable in the same running event handler to immediately contain the new state.

For example:

dispatch({ type: "increment" });

console.log(state.count);

The state value here represents the state from the current render.

The new state will be available during the next render.

Conceptually:

Current render
      ↓
dispatch()
      ↓
React processes update
      ↓
New render
      ↓
New state available

This is similar to how useState updates behave.


51. Important point: dispatch identity

React's dispatch function has a stable identity.

You can safely use it in event handlers and pass it to child components.

For example:

<button
  onClick={() =>
    dispatch({ type: "increment" })
  }
>
  Increment
</button>

This is one reason reducer-based state management works well with Context.


52. Important point: don't dispatch during rendering

Avoid:

function Component() {
  const [state, dispatch] = useReducer(
    reducer,
    initialState
  );

  dispatch({ type: "increment" });

  return <div>{state.count}</div>;
}

This can cause repeated renders and potentially an infinite render loop.

Dispatch from appropriate places such as:

  • event handlers
  • effects
  • callbacks

For example:

onClick={() =>
  dispatch({ type: "increment" })
}

53. A practical decision guide

Ask these questions:

Question 1

Is the state simple?

boolean
string
number
simple value

Use:

useState

Question 2

Are there many related state values?

data
loading
error
status

Consider:

useReducer

Question 3

Are there many actions?

add
remove
update
reset

Consider:

useReducer

Question 4

Does the state need to be shared globally?

Consider:

useReducer + Context

or a dedicated state-management library depending on application complexity.


54. Interview-focused questions

What is useReducer?

useReducer is a React Hook used to manage complex state using a reducer function and dispatched actions.

What are the arguments of useReducer?

useReducer(reducer, initialState)

It optionally accepts a third argument for lazy initialization:

useReducer(reducer, initialArg, init)

What does dispatch do?

dispatch sends an action to the reducer.

dispatch({
  type: "increment"
});

What is a reducer?

A reducer is a function that takes the current state and an action and returns the next state.

(state, action) => newState

What is an action?

An action describes what happened and can contain additional data.

{
  type: "ADD_ITEM",
  payload: item
}

Why use useReducer instead of useState?

useReducer is useful when state has complex transitions, multiple related values, or many different actions.

Can a reducer modify state directly?

No. Reducers should treat state as immutable and return a new state.

Can we make API calls inside a reducer?

No. API calls are side effects and should be handled outside the reducer, such as in an event handler or useEffect.

Can useReducer replace Context API?

No. They solve different problems. useReducer manages state transitions; Context provides a way to share values across the component tree.

Can useReducer replace Redux?

For local or moderately shared state, it can sometimes remove the need for Redux. But Redux provides a larger application-wide state-management ecosystem and additional capabilities.


55. The most important pattern to remember

If you remember only one pattern, remember this:

const [state, dispatch] = useReducer(
  reducer,
  initialState
);

Then:

dispatch({
  type: "ACTION_NAME",
  payload: someData
});

And the reducer:

function reducer(state, action) {
  switch (action.type) {

    case "ACTION_NAME":
      return newState;

    default:
      return state;
  }
}

The complete flow is:

User interaction
       ↓
Event handler
       ↓
dispatch(action)
       ↓
reducer(state, action)
       ↓
return new state
       ↓
React updates state
       ↓
Component re-renders

56. Best practices

Keep actions meaningful

Prefer:

{ type: "ITEM_ADDED", payload: item }

over vague action names.

Keep reducers pure

Don't perform API calls, timers, DOM operations, or other side effects inside reducers.

Never mutate state

Use:

{ ...state }

and immutable array operations such as:

map()
filter()

Use TypeScript unions

Instead of:

action: any

prefer:

type Action =
  | { type: "ADD"; payload: Product }
  | { type: "REMOVE"; payload: number };

Keep reducers focused

A reducer should manage one logical state domain.

Don't use useReducer unnecessarily

Simple state is often better with useState.

Use Context when sharing is required

For example:

useReducer + Context

is a useful pattern for authentication or cart state.


57. useReducer cheat sheet

Concept Meaning
state Current state
dispatch Sends an action
reducer Calculates next state
action Describes what happened
type Identifies the action
payload Data associated with the action
initialState Starting state
return New state
Immutability Don't modify existing state
Pure reducer Same input → same output
useEffect Handles side effects
Context Shares reducer state

58. Final mental model

Think about useReducer like a traffic controller for state changes.

Instead of every component event directly changing state:

Button → change state
Input  → change state
API    → change state
Form   → change state

everything goes through actions:

Button ──┐
Input  ──┤
API    ──┼──→ dispatch(action)
Form   ──┘          ↓
                 Reducer
                    ↓
               New State
                    ↓
               React Render

The reducer becomes the central place that answers:

"Given the current state and what just happened, what should the new state be?"

That is the core idea behind useReducer.

59. Summary

  • useReducer is a React Hook for managing state.
  • It is especially useful for complex state logic.
  • It uses three major concepts: state, dispatch, and reducer.
  • dispatch() sends an action.
  • The reducer receives the current state and action.
  • The reducer returns the new state.
  • React then re-renders the component with the new state.
  • Actions normally contain a type and optionally a payload.
  • Reducers should be pure and should not mutate existing state.
  • API calls and other side effects should happen outside the reducer.
  • useReducer works especially well with Context API for shared application state.
  • TypeScript discriminated unions are an excellent way to type reducer actions.
  • Use useState for simple state.
  • Use useReducer when state transitions become complicated or several related values are managed together.
  • useReducer is not automatically a performance optimization; its main benefit is clear, centralized, predictable state transitions.
← Back to Articles