Sub topic 1
Where useState starts to strain
useState is the right default for most state in a React component. This chapter shows where it stops being comfortable, so that the reducer pattern in the next chapters solves a problem you can already see. You will not write a reducer yet. The goal is to recognize the warning signs in code you already write.
Prerequisites
This chapter assumes you can do the following:
- Write JavaScript functions and use objects, arrays, and the spread operator (
...). - Read and write React function components and JSX.
- Use
useState, including what happens when you call a setter and the component re-renders. - Pass props and attach event handlers such as
onClickandonChange.
You do not need any prior knowledge of reducers, Redux, or useReducer.
A quick recap of useState
useState(initial) returns a pair: the current value and a setter function. Calling the setter schedules a re-render with the new value.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}The setter accepts either a new value or an updater function. An updater function receives the latest pending state and returns the next one:
setCount(prev => prev + 1);This works well when state is a single independent value, like a toggle, a text input, or a counter. The trouble starts when state grows in number and in relationships.
Strain 1: Fields that must change together
Consider a component that loads a user. Three pieces of state describe one situation: whether a request is running, what came back, and whether it failed.
import { useState } from 'react';
export default function Profile({ userId }) {
const [isLoading, setIsLoading] = useState(false);
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
async function load() {
setIsLoading(true);
try {
const res = await fetch(`/api/users/${userId}`);
if (!res.ok) throw new Error('HTTP ' + res.status);
setUser(await res.json());
} catch (e) {
setError(e.message);
}
setIsLoading(false);
}
return (
<>
<button onClick={load} disabled={isLoading}>Load</button>
{isLoading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
{user && <pre>{JSON.stringify(user, null, 2)}</pre>}
</>
);
}This looks fine, and it works on the first click. It has a bug that appears on the second click:
- The first request fails.
erroris set to"HTTP 500". - The user clicks Load again.
loadsetsisLoadingto true but never clearserror. - The second request succeeds.
useris set, anderroris still there.
The screen now shows an error message and a user record together. Nothing in the code forbids that combination. Three independent booleans and nullable values can represent 2 × 2 × 2 = 8 combinations, but only about four are meaningful: idle, loading, success, and error. The other combinations are impossible states, and useState gives you no way to rule them out. You must remember to reset every related field in every handler.
The fix is to set all three fields on every transition:
async function load() {
setIsLoading(true);
setError(null);
setUser(null);
// ...request code
}That fixes this bug, but the rule "update all three together" now lives only in your head and in each handler that touches these fields.
Strain 2: Update logic spread across handlers
When state is a collection, every handler that changes it carries a piece of the update logic. Here is a task list managed with useState:
import { useState } from 'react';
let nextId = 0;
export default function TaskList() {
const [tasks, setTasks] = useState([]);
const [text, setText] = useState('');
function handleAdd() {
setTasks([...tasks, { id: nextId++, text, done: false }]);
setText('');
}
function handleToggle(id) {
setTasks(tasks.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
}
function handleDelete(id) {
setTasks(tasks.filter(t => t.id !== id));
}
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<button onClick={handleAdd}>Add</button>
<ul>
{tasks.map(t => (
<li key={t.id}>
<label>
<input
type="checkbox"
checked={t.done}
onChange={() => handleToggle(t.id)}
/>
{t.text}
</label>
<button onClick={() => handleDelete(t.id)}>Delete</button>
</li>
))}
</ul>
</>
);
}Three handlers is manageable. Now imagine the requirements grow: edit a task, clear completed tasks, mark all done, reorder, undo. Each new feature adds another handler with its own setTasks call. To answer the question "what are all the ways tasks can change?" you have to read the whole component. As the component gets longer, the update rules are buried between rendering code and event wiring.
The handlers also mix two jobs: deciding what happened (the user toggled task 3) and computing the next state (map over the array, flip one flag). A reducer separates those jobs. You will build that in the coming chapters.
Strain 3: Updates that depend on the previous state
State updates in React are not applied immediately. The value you read in a handler is a snapshot from the render that created the handler. This catches many people out:
import { useState } from 'react';
export default function TripleClick() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
return <button onClick={handleClick}>Count: {count}</button>;
}One click raises the count by 1, not 3. All three calls read the same count from the snapshot, so each one schedules "set to 1". With an updater function each call receives the latest queued value:
function handleClick() {
setCount(prev => prev + 1);
setCount(prev => prev + 1);
setCount(prev => prev + 1);
}Now one click adds 3. Updater functions are the right tool, and they are the first step toward the reducer idea: the update is a function from old state to new state, separate from the event that triggered it. The trouble is that you must remember to use the updater form wherever the next value depends on the previous one. When several fields are involved, you need one updater per setter, and the updaters cannot see each other's results.
Strain 4: Logic that is hard to test and reuse
With useState, the update logic is inside a component. To test that toggling a task flips only that task, you have to render the component, find the checkbox, click it, and inspect the DOM. You cannot call the logic directly, because it is a closure over tasks and setTasks.
If two components need the same update rules, you either copy the handlers or extract them into a custom hook. A custom hook is a fine solution, but you still cannot test the rules without rendering something.
A plain function that takes a state and returns a new state avoids both problems. Here is a preview of what such a function looks like for the task list. Do not worry about the details yet, because the next chapter walks through them:
function tasksUpdate(tasks, event) {
switch (event.type) {
case 'added':
return [...tasks, { id: event.id, text: event.text, done: false }];
case 'toggled':
return tasks.map(t =>
t.id === event.id ? { ...t, done: !t.done } : t
);
case 'deleted':
return tasks.filter(t => t.id !== event.id);
default:
throw Error('Unknown event: ' + event.type);
}
}
console.log(tasksUpdate([], { type: 'added', id: 1, text: 'Write tests' }));
// [ { id: 1, text: 'Write tests', done: false } ]You can run that in Node or a browser console with no React at all. Every way the list can change is in one place, and each branch is small enough to read at a glance.
How to tell that useState is straining
No single symptom means you must switch. Look for several of them together:
| Symptom | Example | Why it hurts |
|---|---|---|
| Several fields change in the same handler | `setIsLoading`, `setError`, `setUser` in every transition | Easy to forget one, which produces impossible states |
| Many handlers call the same setter | Add, toggle, delete, clear all call `setTasks` | Update rules are scattered through the component |
| Next state depends on previous state in several fields | Counters, totals, selection, history | Snapshots and stale values cause off-by-one bugs |
| State is a nested object or array | Cart with items, quantities, and totals | Each handler rebuilds part of the structure by hand |
| You want to test the update rules directly | "Clearing completed keeps pending tasks" | Logic cannot be called without rendering |
What to carry forward
Three ideas from this chapter lead into the next one:
- Related fields should change as a unit. Separate setters let them drift apart.
- A state update is a function from the old state and a description of what happened to the new state. Updater functions like
prev => prev + 1already follow this shape. - If that function lives outside the component, it is easy to read in one place and to test without rendering.
The next chapter writes that function properly. It has a fixed signature, (state, action) => nextState, and it is called a reducer.
Exercise
A component keeps isSubmitting, errorMessage, and submittedData in three separate useState calls. The submit handler calls setIsSubmitting(true) and, on success, setSubmittedData(data). After a failed submit followed by a successful one, the page shows both the old error and the new data. (1) Explain the cause. (2) Name the kind of problem this is. (3) Give one change that fixes it without a reducer.
Show answer
(1) The success path never clears errorMessage, because nothing ties the three fields together. The error set by the first attempt stays in state while the second attempt sets the data. (2) It is an impossible state: a combination of values (error present and data present) that the UI was never meant to show, but that three independent setters allow. (3) Reset the related fields at the start of each submit, for example call setErrorMessage(null) and setSubmittedData(null) next to setIsSubmitting(true). A single state object or a status field would also work, and a reducer makes this guarantee structural.
Exercise
In the TripleClick component, handleClick calls setCount(count + 1) three times and the count rises by 1. Why, and how do you make a single click raise it by 3?
Show answer
Each call reads count from the same render snapshot, so all three calls schedule the same value (count + 1). Use updater functions so each call receives the latest queued state: setCount(prev => prev + 1) three times.