Displays count starting at 0. Clicking increment adds 1 each time.
Note setState triggers a re-render. The state value remains the same within the current render cycle even after calling setState -- the new value appears on the next render.
useStatemanage statecomponent statestate variablebasic state
Updater Function
syntax
setState(prevState => newState);
example
function StepCounter() {
const [count, setCount] = useState(0);
function incrementThree() {
// Each updater receives the latest pending state
setCount(prev => prev + 1);
setCount(prev => prev + 1);
setCount(prev => prev + 1);
}
return (
<button onClick={incrementThree}>
Count: {count}
</button>
);
}
output
Each click adds 3 to the count, because each updater builds on the previous pending value.
Note Always use the updater form when the next state depends on the previous state. Writing setCount(count + 1) three times in a row would only add 1 because count is a stale snapshot from the current render.
updater functionprevious statefunctional updateincrement statestate based on previous
function FilteredList() {
// Expensive computation runs only on mount, not every renderconst [sortedItems, setSortedItems] = useState(() => {
const saved = localStorage.getItem('cachedItems');
return saved ? JSON.parse(saved) : [];
});
return <ItemList items={sortedItems} />;
}
Note Pass a function (not the result of calling it) to avoid running expensive initialization logic on every render. React only calls the initializer function during the first render and ignores it on subsequent renders.
lazy initializationexpensive initial stateinitial state functionlocalStorage state
Note Always spread the previous object to create a new copy. Directly mutating state (profile.firstName = 'X') will NOT trigger a re-render because React compares by reference.
Note Use filter to remove, map to update, and spread to add. Never use push, splice, or direct index assignment on state arrays -- those mutate the existing array instead of creating a new one.
array stateadd to arrayremove from arrayupdate array itemtodo list state
Note Separate state variables are preferred when values change independently. Combine into an object only when values logically belong together and always change at the same time.
multiple stateseparate state variablesform statewhen to combine state