From this.setState to State Setters
You'll learn how to replace class component this.setState() calls with the individual setter functions from useState.
The Core Difference
In class components, you called this.setState() with an object or updater function to change state. With hooks, each piece of state gets its own dedicated setter function that updates only that value.
Class component pattern:
this.setState({ count: 5 });
this.setState({ name: "Alice" });
Hooks equivalent:
const [count, setCount] = useState(0);
const [name, setName] = useState("");
setCount(5);
setName("Alice");
Direct Values vs Updater Functions
Both patterns support direct values and updater functions, but the syntax differs slightly.
Class with updater function:
this.setState((prevState) => ({
count: prevState.count + 1
}));
Hooks with updater function:
setCount((prevCount) => prevCount + 1);
Notice that in hooks, the updater function receives the previous value of that specific state variable, not the entire state object. This is cleaner—you only work with the exact piece of data you're updating.
The Mental Shift
Think of this.setState as a single gatekeeper managing a large filing cabinet (your state object). Individual state setters are like having separate keys for each drawer—more direct, more focused. You don't need to merge objects or worry about other state values; each setter handles exactly one thing.
Key Takeaway: Replace this.setState() calls with individual useState setters—use direct values like setCount(5) or updater functions like setCount(prev => prev + 1) for the same behaviors, but with cleaner, more targeted updates.