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
useState | useReducer | |
|---|---|---|
| Code size | small | more upfront (reducer + actions) |
| Update logic | spread across handlers | centralized in the reducer |
| Readability with many updates | degrades | stays clear |
| Testing | through components | reducer is a pure function, easy to unit test |
| Debugging | console.log in handlers | log actions in one place |
| Passing to children | several setters | one stable dispatch |
Signals you should switch to useReducer
- Multiple
useStatecalls 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";23// useState: fine for a simple toggle4export function Toggle() {5 const [on, setOn] = useState(false);6 return <button onClick={() => setOn((o) => !o)}>{on ? "On" : "Off"}</button>;7}89// useReducer: a fetch state machine with rules10type State =11 | { status: "idle" }12 | { status: "loading" }13 | { status: "success"; data: string[] }14 | { status: "error"; error: string; retries: number };1516type Action = { type: "fetch" } | { type: "resolve"; data: string[] } | { type: "reject"; error: string };1718function 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}2829export 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.