Skip to content

Instantly share code, notes, and snippets.

@attitude
Created June 23, 2025 16:08
Show Gist options
  • Select an option

  • Save attitude/3f15b7f32040114f9f59adbad1e09c60 to your computer and use it in GitHub Desktop.

Select an option

Save attitude/3f15b7f32040114f9f59adbad1e09c60 to your computer and use it in GitHub Desktop.
Use a callback function with stable identity
/**
* Returns a stable callback function whose identity does not change between renders,
* but always invokes the latest version of the provided callback.
*
* This is useful when you need to pass a callback to a dependency array or a child component,
* and want to avoid unnecessary re-renders or effect executions caused by changing function references,
* while still ensuring the callback always has access to the latest props and state.
*
* @template T - The type of the callback function.
* @param callback - The callback function to be stabilized.
* @returns A stable function that always calls the latest version of the provided callback.
*/
export function useStableCallback<T extends (...args: any[]) => any>(callback: T): T {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
return useCallback((...args: any[]) => callbackRef.current(...args), []) as T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment