The "Latest Ref" Pattern
Sometimes you want to use a function inside useEffect, but you don't want that function to trigger the effect when it changes.
function useInterval(callback, delay) {
const savedCallback = useRef(callback);
// Always keep the latest callback in a ref
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
function tick() {
// Call the ref, not the prop directly
savedCallback.current();
}
const id = setInterval(tick, delay);
return () => clearInterval(id);
}, [delay]); // 'callback' is NOT a dependency!
}
This pattern is so useful it is being standardized in React 19 as useEvent.
Sponsored Content
Google AdSense Placeholder
CONTENT SLOT