Menu

1 / 2

useCallbackRef: A Stable Callback That Never Goes Stale

DEV Community: typescript·Saiful Islam·1 day ago
#sePy4giv
#devtotypescript#devto#dev#callback#render
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.