0 day streak
javascript / expert
Snippet

Stabilizing Callbacks with the Event Hook Pattern

This pattern solves the trade-off between stale closures and unnecessary re-renders. By storing the latest handler in a ref and returning a memoized wrapper, the returned function reference remains stable across renders while always having access to the latest scope variables.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
function useEvent(handler) {
const handlerRef = useRef(handler);
useLayoutEffect(() => {
handlerRef.current = handler;
});
return useCallback((...args) => {
return handlerRef.current(...args);
}, []);
}
react
Breakdown
1
const handlerRef = useRef(handler);
Initializes a mutable reference to hold the current version of the function.
2
useLayoutEffect(() => { handlerRef.current = handler; });
Updates the reference synchronously after DOM mutations but before browser paint to ensure no stale versions exist.
3
return useCallback((...args) => handlerRef.current(...args), []);
Returns a function that never changes its identity, preventing downstream re-renders.