Created
July 17, 2022 03:18
-
-
Save itsMapleLeaf/8a28ffd0eb54a9ef7964627d9cc1be35 to your computer and use it in GitHub Desktop.
React 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" | |
export function useEvent<Args extends unknown[], Return>( | |
callback: (...args: Args) => Return, | |
) { | |
const ref = useRef((...args: Args): Return => { | |
throw new Error("Attempt to call event callback during render") | |
}) | |
useLayoutEffect(() => { | |
ref.current = callback | |
}) | |
return useCallback((...args: Args) => ref.current(...args), []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment