Lesson 16 of 28Article16 min
useState Hook
useState returns a value and a setter function. Calling the setter tells React to re-render with the new value.
useState — local component state
useState returns a value and a setter function. Calling the setter tells React to re-render with the new value.
State is private to the component unless you lift it up or share via Context.
Real-life example: useState is a whiteboard in your room. You erase and write new numbers (setState); visitors see the updated board (re-render).
Counter with useState
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount((c) => c - 1)}>-1</button>
</div>
);
}Object and array state
Never mutate state directly. For objects and arrays, spread the old value and change one field.
Real-life example: Updating object state is editing a Google Doc copy — you save a new version; you do not scribble on the archived PDF.
Functional updates (setCount(c => c + 1)) are safest when the new value depends on the previous value.
Object state update
const [user, setUser] = useState({ name: "", score: 0 });
setUser((prev) => ({ ...prev, score: prev.score + 10 }));
// Functional update when new state depends on old
setCount((c) => c + 1);