Managing Events and State
Watch the walkthrough
Open on InstagramQuick revision
Pass an event handler: onClick={handleClick}. Calling handleClick() there executes it while rendering. A controlled input reads its value from state and writes changes back through onChange.
State belongs to a render snapshot. Calling a setter schedules the next render; it does not change the variable captured by the current handler. When an update depends on the previous value, pass an updater such as setCount(count => count + 1). React can batch updates, and queued updaters compose in order.
Follow the repository example
input stores the draft text and items stores submitted entries. setItems(prev => [...prev, input]) creates a new array rather than mutating the old one. Extend the handler to trim whitespace, reject empty entries, and clear the draft after submission. Give inserted entries stable IDs if they can later be removed or reordered.
Recall check
Three calls to setCount(count + 1) in the same handler use the same snapshot. Three calls to setCount(c => c + 1) apply three sequential increments.
References: Responding to events, State as a snapshot, and Queued state updates.