This article explores the functional update patterns in React's useState hook, specifically lazy initializers and functional state updates. It explains how to prevent unnecessary computation during re-renders and how to avoid stale state issues in asynchronous or rapid updates.
Key points
Passing a function to useState serves as a lazy initializer, ensuring expensive initialization logic runs only on the initial render.
Providing a function to the dispatch/setter function ensures you always work with the most recent state value, avoiding stale closures.
Functional updates are essential when state changes depend on the previous state value.
Standard variables within a component body are recalculated on every re-render; lazy initializers mitigate this performance cost for expensive operations.