Last active
March 26, 2024 04:33
-
-
Save btoo/ae5dfcb1ccebf5496352365d1f1434a1 to your computer and use it in GitHub Desktop.
typescript type-safe version of the approximate implementation of react's (no longer) proposed useEvent hook
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 { useCallback, useLayoutEffect, useRef } from 'react'; | |
/** typescript type-safe version of [the approximate implementation of react's (no longer) proposed `useEvent` hook](https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#internal-implementation) */ | |
export function useEvent<Args extends Array<unknown>, Return>( | |
handler: (...args: Args) => Return, | |
): typeof handler { | |
const handlerRef = useRef(handler); | |
useLayoutEffect(() => { | |
handlerRef.current = handler; | |
}); | |
return useCallback((...args) => handlerRef.current(...args), []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment