Skip to content

Instantly share code, notes, and snippets.

@hamzakaya
Created May 12, 2022 20:35
Show Gist options
  • Save hamzakaya/b05ab1d07e751108a86c4d715abf9cd8 to your computer and use it in GitHub Desktop.
Save hamzakaya/b05ab1d07e751108a86c4d715abf9cd8 to your computer and use it in GitHub Desktop.
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