Skip to content

Instantly share code, notes, and snippets.

@Grohden
Created October 29, 2020 14:23
Show Gist options
  • Save Grohden/a773e9aefec115a62a2c34eb286a2ad6 to your computer and use it in GitHub Desktop.
Save Grohden/a773e9aefec115a62a2c34eb286a2ad6 to your computer and use it in GitHub Desktop.
Automatic ref callback for react
import { useRef, useCallback } from 'react';
/**
* Creates a stable callback pointing to the **latest
* render** [callback] provided to this function, making it stable
* without specifying deps.
*
* Note: Don't use this for render callbacks, this will cause
* renders to not update properly when state changes.
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export const useRefCallback = <T extends Function>(callback: T) => {
const ref = useRef(callback);
ref.current = callback;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (useCallback((...args: any) => {
ref.current(...args);
}, []) as unknown) as T; // this T cast will make sure we have correct args
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment