State
Props come from the outside and do not change. State is information that the component manages and can change over time (a counter, text being typed...). When state changes, React re-renders the component.
State is declared with the useState hook:
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Add</button>
</div>
);
}
useState(0)creates a state with initial value0.- It returns an array: the current value (
count) and a function to change it (setCount). - Never modify state directly (
count++). Always use the function (setCount(...)): that is what tells React it must repaint.
In the exercises,
useState(and other hooks) are already available: you can use them directly, without importing them.