State and Event Handling
Props let data flow in from a parent, state lets a component remember and update its own data over time. The useState hook is how you add state to a function component.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
How it works
useState(0)returns a pair, the current value (count) and a setter function (setCount), starting at0.- Calling
setCount(...)tells React the value changed, React then re-renders the component with the new value. onClick={() => setCount(count + 1)}attaches an event handler, the same pattern works foronChange,onSubmit, and every other DOM event.
WARNING
Never mutate state directly (count++ or count = count + 1), always go through the setter, or React won't know to re-render.