31. Why are state updates asynchronous?
State updates are asynchronous because React batches multiple updates together and processes them efficiently. This improves performance by reducing unnecessary re-renders and ensuring the UI updates in an optimized way.
Example
function Counter() {
const [count, setCount] = React.useState(0);
const handleClick = () => {
setCount(count + 1);
console.log(count); // Still shows old value
};
}The console.log shows the old value because React schedules the state update and applies it during the next render.
Benefits
Better performance through batching
Fewer re-renders
Smoother UI updates
More efficient rendering process
Getting the Latest Value
setCount(prev => prev + 1);Use the functional update form when the new state depends on the previous state.
Summary: State updates are asynchronous so React can batch and optimize updates, reducing unnecessary renders and improving application performance.