Last active
August 23, 2023 02:53
-
-
Save itsMapleLeaf/7dd96915194bd7a3b9be89306005be8d to your computer and use it in GitHub Desktop.
This file contains 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, useInsertionEffect, useRef } from "react" | |
export function useEffectEvent<Args extends unknown[], Return>( | |
callback: (...args: Args) => Return, | |
) { | |
const ref = useRef((..._args: Args): Return => { | |
throw new Error("Cannot call an event handler while rendering.") | |
}) | |
useInsertionEffect(() => { | |
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