Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Last active July 23, 2024 19:21
Show Gist options
  • Save itsMapleLeaf/7dd96915194bd7a3b9be89306005be8d to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/7dd96915194bd7a3b9be89306005be8d to your computer and use it in GitHub Desktop.
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