Capítulo 21 de 116
A regular local variable doesn't survive a re-render and doesn't cause one when changed — useState solves both problems, giving a component a value React remembers across renders and a setter that schedules a new render with the updated value.
const [index, setIndex] = useState(0): useState's only argument is the initial value; it returns a [value, setter] pair. The [something, setSomething] naming is convention, not required.useState(0) returns [0, setIndex], React remembers 0. Event fires setIndex(1) → React remembers 1 and schedules a re-render. Next render → useState(0) is called again (same argument!) but React returns [1, setIndex] because it now remembers 1, not the literal argument passed.useState as many times as it needs — each call is independently tracked (order matters, hence the Rules of Hooks in Ch 116).<Gallery /><Gallery />) gives each instance its own completely independent state — updating one never affects the other. This is the same isolation seen with the two-counter example in Ch 1, now explained mechanically.const [index, setIndex] = useState(0);
function handleNextClick() {
setIndex(index + 1);
}
useState shape — an initial value in, a [value, setter] pair out, and a setter call that both updates the remembered value and schedules a re-render.useState's argument is only ever read on the very first render — treat it purely as "initial value," not as something React re-applies on every call.useState multiple times rather than cramming everything into one state object, unless the values are tightly related and always change together.setIndex call actually schedules.index inside a handler doesn't update mid-function even after calling the setter.