Sub topic 7
useState or useReducer?
This chapter assumes you can write a function component with useState, and that you know how a reducer takes (state, action) and returns the next state. It also assumes you can write immutable updates with spread, map, and filter. Here you decide which hook fits a given piece of state.
Same behavior, different shape
useState and useReducer both store state and trigger a re-render when it changes. useState is built on the same mechanism as useReducer. The difference is where the update logic lives.
- With
useState, each event handler computes the next value and passes it to a setter. - With
useReducer, handlers only describe what happened by callingdispatch. One reducer function decides how the state changes.
| Concern | useState | useReducer |
|---|---|---|
| Code size for simple state | Smaller | More boilerplate (reducer and action types) |
| Update logic location | Spread across handlers | Centralized in the reducer |
| Related fields that change together | Several setters, which can drift out of sync | One action updates them in a single step |
| Next state depends on the previous one | Works, but gets verbose | Natural, since the reducer receives the current state |
| Testing the logic | Render the component | Call the reducer as a plain function |
| Passing updates to deep children | One setter per kind of change | One stable `dispatch` |
When state outgrows useState
Here is a typical useState version of a multi-step form.
import { useState } from 'react';
export default function Signup() {
const [step, setStep] = useState(1);
const [email, setEmail] = useState('');
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState(null);
function handleSubmit() {
setSubmitting(true);
setError(null);
// ...start the request. On failure you must remember to
// call setSubmitting(false) and setError(...) together.
}
return <button onClick={handleSubmit}>Submit step {step}</button>;
}Every handler has to update the right combination of setters. If one handler forgets setSubmitting(false), the form can get stuck in a state that should be impossible, such as submitting: true with an error showing.
A reducer turns that combination into one named event.
import { useReducer } from 'react';
const initialState = { step: 1, email: '', submitting: false, error: null };
function signupReducer(state, action) {
switch (action.type) {
case 'email_changed':
return { ...state, email: action.email };
case 'submit_started':
return { ...state, submitting: true, error: null };
case 'submit_failed':
return { ...state, submitting: false, error: action.error };
case 'submit_succeeded':
return { ...state, submitting: false, step: state.step + 1 };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Signup() {
const [state, dispatch] = useReducer(signupReducer, initialState);
return (
<>
<input
value={state.email}
onChange={e => dispatch({ type: 'email_changed', email: e.target.value })}
/>
<button onClick={() => dispatch({ type: 'submit_started' })}>
{state.submitting ? 'Sending...' : 'Submit'}
</button>
{state.error && <p>{state.error}</p>}
</>
);
}submit_failed always clears submitting and sets error in the same step. A handler can't forget half of it.
A decision guide
Choose useReducer when one or more of these is true:
- Several fields must change together, as in the form above.
- Many handlers update the same state, so you want the rules in one place.
- You want to unit test the update logic without rendering.
- You plan to share updates through context with a single
dispatch.
Stay with useState for toggles, text inputs, and other independent values. A reducer there adds code and nothing else.
Common errors
- Switching too early. Converting every
useStateto a reducer makes simple components harder to read. Start withuseStateand move when handlers start to repeat or drift. - Mutating state in the reducer.
state.count++ortodos.push(x)breaks re-rendering and Strict Mode checks. Return new objects and arrays. - Putting side effects in the reducer. Fetching or writing to storage belongs in an event handler or
useEffect. The reducer only computes the next state. - Vague action names.
{ type: 'update' }hides what happened. Name actions after the event, such assubmit_failed.
Exercise
A component keeps isOpen in state and only toggles it from one button. Another component keeps items, filter, and selectedId, and several handlers update two or three of these at once. Which hook fits each one, and why?
Show answer
Use useState for isOpen. It is a single independent value with one update path, so a reducer adds boilerplate for no gain. Use useReducer for the second component. Its fields change together, so one reducer can update them in a single step, and the logic can be tested without rendering.