Sub topic 7
useState or useReducer?
This chapter helps you choose between useState and useReducer for a given piece of state. It assumes you can write a reducer and call useReducer, and that you know useState, immutable updates with spread, and basic event handling. It doesn't re-teach those.
The short answer
Both hooks store a value between renders and re-render the component when it changes. The difference is where the update logic lives.
- With
useState, each event handler calls a setter and decides the next value itself. - With
useReducer, handlers only describe what happened by dispatching an action. One reducer function decides the next value.
Neither hook is more advanced or more correct. Use the one whose trade-offs fit the state in front of you.
What each hook costs
| Concern | useState | useReducer |
|---|---|---|
| Code for a simple value | A line or two | A reducer, an initial state, and action types |
| Update logic location | Spread across event handlers | Centralized in one function |
| Several fields that change together | Several setters, which you must keep in sync | One action produces the whole next state |
| Reading the history of changes | Search every setter call | Read the list of action types |
| Testing the logic | Render the component | Call the reducer with a state and an action |
| Passing updates to deep children | Pass several setters or wrap them | Pass one stable `dispatch` |
| Debugging | Log inside handlers | Log every action in one place |
Signs that useState is enough
Stay with useState when most of these are true:
- The state is a single value, such as a boolean, a string, or a number.
- Fields are independent. Changing one never requires changing another.
- Each update is a plain replacement, like
setName(e.target.value). - Only one or two handlers touch the state.
A form with independent text inputs is the typical case. A reducer here only adds ceremony.
import { useState } from 'react';
export default function ProfileForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
return (
<form>
<input value={name} onChange={e => setName(e.target.value)} />
<input value={email} onChange={e => setEmail(e.target.value)} />
</form>
);
}Writing 'name_changed' and 'email_changed' actions for this form would be the same code with more steps.
Signs that useReducer pays off
Consider useReducer when you see any of these.
Several fields must change together
Whenever a handler calls three setters in a row, a bug can hide in the gap between them. Here is a component that tracks an upload with three separate pieces of state:
import { useState } from 'react';
export default function Upload({ send }) {
const [isSending, setIsSending] = useState(false);
const [sent, setSent] = useState(false);
const [error, setError] = useState(null);
async function handleClick() {
setIsSending(true);
try {
await send();
setSent(true);
} catch (e) {
setError(e.message);
}
setIsSending(false);
}
return (
<>
<button onClick={handleClick} disabled={isSending}>Send</button>
{error && <p>Error: {error}</p>}
{sent && <p>Sent!</p>}
</>
);
}Suppose the first click fails and the second succeeds. error is never cleared, and sent is now true as well. The screen shows both "Error" and "Sent!". Three booleans allow eight combinations, and only four of them make sense. Nothing in the code prevents the other four.
The reducer version has one status field, so contradictory combinations cannot be written:
import { useReducer } from 'react';
const initialState = { status: 'idle', error: null };
function uploadReducer(state, action) {
switch (action.type) {
case 'send_started':
return { status: 'sending', error: null };
case 'send_succeeded':
return { status: 'sent', error: null };
case 'send_failed':
return { status: 'failed', error: action.error };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Upload({ send }) {
const [state, dispatch] = useReducer(uploadReducer, initialState);
async function handleClick() {
dispatch({ type: 'send_started' });
try {
await send();
dispatch({ type: 'send_succeeded' });
} catch (e) {
dispatch({ type: 'send_failed', error: e.message });
}
}
return (
<>
<button onClick={handleClick} disabled={state.status === 'sending'}>
Send
</button>
{state.status === 'failed' && <p>Error: {state.error}</p>}
{state.status === 'sent' && <p>Sent!</p>}
</>
);
}Every action sets every field, so send_started always clears the old error. The reducer now holds the rules for what a valid state looks like.
The next state depends on the previous one in non-trivial ways
Toggling one todo, deleting another, and clearing all completed items each need the current list. In useState you would write these with functional updates in three handlers. In a reducer they sit side by side in one switch, where you can compare them.
Many handlers update the same state
When ten handlers each build a new object, the same shape rules get repeated ten times. Changing the shape means editing ten places. With a reducer you change one.
You want to test or inspect the logic
A reducer is a pure function. You can test it without rendering anything, and you can log (state, action) pairs to see exactly how the state evolved. A bug report that includes the list of dispatched actions is far easier to reproduce than one that says "I clicked around."
Deep children need to update the state
Passing one dispatch through context replaces passing a setter per operation. React keeps dispatch identical across renders, so it won't cause child re-renders by changing.
Costs of useReducer
Be honest about the price before switching.
- It takes more code up front. A reducer, an initial state, and action names are overhead for a simple value.
- Reading a handler means jumping to the reducer to learn what the action does.
- Weak action design brings back the problems you wanted to leave. An action like
{ type: 'set_field', field, value }is only a setter in disguise. - Reducers must be pure. You can't fetch, write to storage, or set timers inside one. Side effects stay in handlers or effects.
Mixing both in one component
You don't have to choose once per component. A common split is useState for ephemeral, independent UI values and useReducer for state with rules.
In the todo example from earlier chapters, the text in the input box is useState. The list of todos is useReducer. Typing a letter doesn't need to pass through a reducer, and adding or toggling a todo does benefit from one.
A decision flow
Treat the diagram as a starting heuristic. If a component's state is awkward to read, try the other hook and compare the two versions.
Common mistakes when choosing
- Switching because reducers feel more professional. A simple counter does not need one. Choose based on the state's shape.
- Keeping several booleans that exclude each other. If
isLoading,isError, andisSuccesscan't all be true, use onestatusstring, withuseStateoruseReducer. The status field fixes the impossible states. The reducer just makes transitions explicit. - Storing derived data. If
visibleTodoscan be computed fromtodosand a filter, compute it during render. Don't put it in the reducer state. - Writing actions as setters. Name actions after what happened (
'todo_toggled'), not what to change ('set_todo_done'). The reducer decides the consequences. - Doing side effects in the reducer. React may call a reducer twice in Strict Mode to detect impurity. A network call or a random ID inside a reducer will misbehave. Generate IDs and make requests in handlers or effects, and pass the results in the action.
- Forgetting to return state. A
switchcase that falls through without returning givesundefined, and your component then crashes onstate.count. Thedefault: throwbranch in the examples catches mistyped action names early.
Migrating from useState to useReducer
You can convert gradually. The steps are mechanical:
- List the pieces of state that change together and merge them into one object.
- For each handler, name the event it responds to (
'item_added', not'set_items'). - Move the update logic from each handler into a
casein the reducer. - Replace the setter calls with
dispatch({ type, ...data }). - Delete the old
useStatecalls.
After step 4 the component should read as a list of events. If a handler still computes new state before dispatching, move that computation into the reducer.
Exercise
A checkout component has these state variables: const [items, setItems] = useState([]), const [coupon, setCoupon] = useState(''), const [discount, setDiscount] = useState(0), and const [isApplying, setIsApplying] = useState(false). Applying a coupon sets isApplying, then updates discount and clears coupon on success. Removing an item also recalculates discount. Which of these would you move into a reducer, which would you keep as useState, and what two action names would you use?
Show answer
Keep coupon as useState, because it is a text input value that changes independently on every keystroke. Move items, discount, and isApplying into one reducer, because they change together and the discount depends on the items. Two possible action names are 'coupon_applied' (set the discount, clear isApplying) and 'item_removed' (remove the item and recompute the discount). A third, 'coupon_apply_started', would set isApplying to true. The coupon text is cleared in the handler by calling setCoupon('') when it dispatches 'coupon_applied'. The reducer must not do that itself, because coupon lives outside it.