AZ.dev

Update state from its previous value without losing updates

| react: 16+

Pass a function to the setter when the new value depends on the old one. React calls it with the latest state, however many updates are queued.

setCount((c) => c + 1);

The plain form reads count from the render the handler was created in, so two of them in a row both see the same number:

setCount(count + 1);
setCount(count + 1); // still count + 1, not count + 2

Where it bites

When the plain form is fine

Setting to a value that doesn’t depend on the previous one: setOpen(true), setQuery(e.target.value). An updater there adds nothing.

Gotchas

useState setState updater batching closures

This entry is one card on a printable cheat sheet:

React Essentials Cheat Sheet

Was this helpful?

Related Entries

Reset a component's state when the thing it shows changesWhy useEffect runs twice in development and how to write it so that's fine