ReactMedium

useReducer vs useState?

Use useState for simple, independent values updated in a few ways. Use useReducer when state has several related fields, when the next state depends on the previous in complex ways, or when many events update the same state. Both trigger re-renders the same way; the difference is how you organize update logic.

Comparison

useStateuseReducer
Code sizesmallmore upfront (reducer + actions)
Update logicspread across handlerscentralized in the reducer
Readability with many updatesdegradesstays clear
Testingthrough componentsreducer is a pure function, easy to unit test
Debuggingconsole.log in handlerslog actions in one place
Passing to childrenseveral settersone stable dispatch

Signals you should switch to useReducer

  • Multiple useState calls that are always updated together.
  • Handlers repeating similar spread logic.
  • State that represents a state machine (loading, success, error, retrying).
  • Deep updates that are easy to get wrong.

You can mix

Use useState for local toggles and useReducer for the main data in the same component.

Beyond component state

If many components across the app need the same reducer-driven state, combine useReducer with context, or move to Redux Toolkit or Zustand.

Code example

tsx
1import { useReducer, useState } from "react";
2
3// useState: fine for a simple toggle
4export function Toggle() {
5 const [on, setOn] = useState(false);
6 return <button onClick={() => setOn((o) => !o)}>{on ? "On" : "Off"}</button>;
7}
8
9// useReducer: a fetch state machine with rules
10type State =
11 | { status: "idle" }
12 | { status: "loading" }
13 | { status: "success"; data: string[] }
14 | { status: "error"; error: string; retries: number };
15
16type Action = { type: "fetch" } | { type: "resolve"; data: string[] } | { type: "reject"; error: string };
17
18function reducer(state: State, action: Action): State {
19 switch (action.type) {
20 case "fetch":
21 return { status: "loading" };
22 case "resolve":
23 return { status: "success", data: action.data };
24 case "reject":
25 return { status: "error", error: action.error, retries: state.status === "error" ? state.retries + 1 : 1 };
26 }
27}
28
29export function Loader() {
30 const [state, dispatch] = useReducer(reducer, { status: "idle" });
31 async function load() {
32 dispatch({ type: "fetch" });
33 try {
34 const data = await fetch("/api/items").then((r) => r.json());
35 dispatch({ type: "resolve", data });
36 } catch (e) {
37 dispatch({ type: "reject", error: (e as Error).message });
38 }
39 }
40 return <button onClick={load}>{state.status === "loading" ? "Loading…" : "Load"}</button>;
41}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app