Created
October 29, 2020 14:23
-
-
Save Grohden/a773e9aefec115a62a2c34eb286a2ad6 to your computer and use it in GitHub Desktop.
Automatic ref callback for react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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