Skip to content

Instantly share code, notes, and snippets.

@HaNdTriX
Last active March 10, 2019 10:42
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 HaNdTriX/db93a8dc32d7e2e36514d6ad206bc520 to your computer and use it in GitHub Desktop.
Save HaNdTriX/db93a8dc32d7e2e36514d6ad206bc520 to your computer and use it in GitHub Desktop.
React hook for reducing the amount of ref event bindings
import { useRef, useEffect } from 'react'
/**
* This hook reduces the amount of rebindings.
* Use it when your props change a lot.
*
* @param {DomRef} targetRef The reference to the dom node
* @param {String} eventName The eventName you want to bind
* @param {Function} handler The actual event handler
*/
function useCachedRefHandler (targetRef, eventName, handler) {
const savedHandler = useRef()
useEffect(() => {
savedHandler.current = handler
}, [handler])
useEffect(() => {
const internalHandler = (...args) => {
if (savedHandler.current) {
savedHandler.current(...args)
}
}
targetRef.current.addEventListener(eventName, internalHandler)
return () => targetRef.current.removeEventListener(eventName, internalHandler)
}, [])
}
export default useCachedRefHandler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment