Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created July 17, 2022 03:18
Show Gist options
  • Save itsMapleLeaf/8a28ffd0eb54a9ef7964627d9cc1be35 to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/8a28ffd0eb54a9ef7964627d9cc1be35 to your computer and use it in GitHub Desktop.
React useEvent hook
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