Skip to content

Instantly share code, notes, and snippets.

@tony
Created September 9, 2019 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tony/326d2974b475e80644335d5bb9727234 to your computer and use it in GitHub Desktop.
Save tony/326d2974b475e80644335d5bb9727234 to your computer and use it in GitHub Desktop.
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