React useLatest Hook: Read Fresh State in Async Callbacks (2026)
Here's an autosave button that lies to the user: function Editor ({ docId }: { docId : string }) { const [ text , setText ] = useState ( "" ); const [ status , setStatus ] = useState < " idle " | " saving " | " saved " | " dirty " > ( " idle " ); async function save () { setStatus ( " saving " ); await api . save ( docId , text ); setStatus ( " saved " ); // ⚠️ but the user kept typing during the…
The React useLatest hook provides a way to read the latest state in asynchronous callbacks, avoiding stale closures that can cause issues with out-of-date data. In the example given, an autosave button in a text editor would sometimes fail to save the user's most recent input due to stale closures within the async save function.
The useLatest hook, from the @reactuses/core package, solves this problem by maintaining a reference to the latest value using a ref object. It does so by using a layout effect (useIsomorphicLayoutEffect) instead of a render effect, which guarantees that the ref's .current property is always updated with the most recent value. This approach allows the useLatest hook to be safely used in various asynchronous callbacks, such as setTimeout, setInterval, event listeners, and third-party SDK callbacks, ensuring that the latest data is always read, regardless of when the callback is executed.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.