Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
LICENSE MIT
import React from 'react'
export const useEventCallback = <T extends (...args: any[]) => any>(
callback: T,
dependencies: React.DependencyList,
) => {
const ref = React.useRef(() => {
throw new Error('Cannot call an event handler while rendering.')
})
React.useEffect(() => {
ref.current = callback as never
}, [callback, ...dependencies])
return React.useCallback(() => {
const callbackC = ref.current
return callbackC()
}, [ref])
}
export default useEventCallback
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment