Props (from the earlier Props lesson) let data flow into a component from outside, but a component can't change its own props. State is the other half: data a component owns and can change itself, over time — a counter, a form field, whether a menu is open.
A regular JavaScript variable inside a component gets reset to its initial value every single time the component re-renders, and changing it doesn't even trigger a re-render in the first place — React has no way to know the value changed:
function Counter() {
let count = 0; // resets to 0 on every render — this does not work
function increment() {
count = count + 1; // React never finds out this happened
}
return <button onClick={increment}>Clicked {count} times</button>;
}useState solves both problems: it gives a component a value that survives between renders, and a way to update it that tells React to re-render:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
return <button onClick={increment}>Clicked {count} times</button>;
}useState(0) takes the initial value and returns a pair: the current value (count) and a function to update it (setCount) — the [a, b] array destructuring here is the same syntax from the JavaScript ES6 lesson.
Calling setCount(...) does two things: it updates the stored value, and tells React to re-run the component function so the UI reflects the new value. This is the actual mechanism behind the "declarative" idea from the Introduction lesson — you never manually touch the DOM; you update state, and React re-renders to match.
function App() {
return (
<div>
<Counter />
<Counter />
</div>
);
}
// Clicking one Counter never affects the other — each has its own independent state.Multiple useState calls are fine
A component can have as many useState calls as it needs — one per independent piece of state is the normal pattern, rather than bundling everything into one big object. const [name, setName] = useState(''); const [age, setAge] = useState(0); is completely normal.