Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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) {
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
You can’t perform that action at this time.