A five-line hook that gives you one function identity for the life of a component while always calling the newest version — and why the swap waits until after paint, not during render.
The Problem
You have an autosave. It is almost right.
import { useEffect , useState } from " react " ;
type Draft = { id : string ; body : string };
function Editor ({ draftId , initialBody , onSave , }: { draftId : string ; initialBody : string ; onSave : ( draft : Draft ) => Promise < void > ; }) { const [ body , setBody ] = useState ( initialBody );
useEffect (() => { const id = setInterval (() => { void onSave ({ id : draftId , body }); // ⚠️ `body` from the mount render }, 5000 ); return () => clearInterval ( id ); }, [ draftId ]);
return ( < textarea value = { body } onChange = { ( event ) => setBody ( event . target . value ) } /> ); }
Enter fullscreen mode
Exit fullscreen mode
You type for two minutes. The save spinner blinks every five seconds.…