Created
May 26, 2024 15:08
-
-
Save ethansnow2012/f3da19942c81402b85d29921e0572687 to your computer and use it in GitHub Desktop.
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, useInsertionEffect, useCallback } from 'react'; | |
// Define a type for the event function | |
type EventFunction = (...args: any[]) => any; | |
export function useEvent<T extends EventFunction>(fn: T): T { | |
const ref = useRef<T | null>(null); | |
useInsertionEffect(() => { | |
ref.current = fn; | |
}, [fn]); | |
return useCallback((...args: Parameters<T>): ReturnType<T> => { | |
const f = ref.current; | |
if (f) { | |
return f(...args); | |
} | |
}, []) as T; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment