JAVASCRIPT
React `useEventCallback` for Stable Callbacks in `useEffect`
Create stable callback functions that can be safely used in `useEffect` dependency arrays without causing unnecessary re-renders or stale closures, improving component performance and reliability.
import { useRef, useEffect, useCallback } from 'react';
function useEventCallback(fn) {
const ref = useRef(fn);
// We need to update the ref on every render so that the
// latest version of the function is always available.
useEffect(() => {
ref.current = fn;
}, [fn]);
// Return a stable function that always calls the latest `fn`.
const stableFn = useCallback((...args) => {
return ref.current(...args);
}, []); // The empty array ensures this function itself is stable
return stableFn;
}
How it works: When a function defined inside a component is used as a dependency in `useEffect`, it often causes the effect to re-run on every render because a new function reference is created. `useEventCallback` solves this by providing a stable function reference that will *always* execute the latest version of the passed `fn`. This is crucial for optimizing effects that depend on callbacks, preventing stale closures, and avoiding unnecessary re-executions of effects.