Skip to content

Instantly share code, notes, and snippets.

@ethansnow2012
Created May 26, 2024 15:08
Show Gist options
  • Save ethansnow2012/f3da19942c81402b85d29921e0572687 to your computer and use it in GitHub Desktop.
Save ethansnow2012/f3da19942c81402b85d29921e0572687 to your computer and use it in GitHub Desktop.
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