Last active
March 10, 2019 10:42
-
-
Save HaNdTriX/db93a8dc32d7e2e36514d6ad206bc520 to your computer and use it in GitHub Desktop.
React hook for reducing the amount of ref event bindings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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