Created
May 12, 2022 20:35
-
-
Save hamzakaya/b05ab1d07e751108a86c4d715abf9cd8 to your computer and use it in GitHub Desktop.
This file contains 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 { useLayoutEffect, useRef } from "react"; | |
type AnyFunction = (...args: any[]) => any; | |
const useLayoutEffectRef = typeof window !== "undefined" ? useLayoutEffect : () => {}; | |
export function useCallbackRef<TCallback extends AnyFunction>(callback: TCallback): TCallback { | |
const latestRef = useRef<TCallback>(useCallbackRef_shouldNotBeInvokedBeforeMount as any); | |
useLayoutEffectRef(() => { | |
latestRef.current = callback; | |
}, [callback]); | |
const stableRef = useRef<TCallback>(null as any); | |
if (!stableRef.current) { | |
stableRef.current = function(this: any) { | |
return latestRef.current.apply(this, arguments as any); | |
} as TCallback; | |
} | |
return stableRef.current; | |
} | |
function useCallbackRef_shouldNotBeInvokedBeforeMount() { | |
throw new Error("useCallbackRef Error"); | |
} | |
export default useCallbackRef; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment