Created
September 19, 2019 03:08
-
-
Save ricokahler/c207aaadc42de3a133490b24c4dddd64 to your computer and use it in GitHub Desktop.
Only add the event listener once
This file contains hidden or 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 React, { useCallback } from 'react'; | |
function usePullValue(value) { | |
const ref = useRef(value); | |
useLayoutEffect(() => { | |
ref.current = value; | |
}, [value]); | |
return useCallback(() => { | |
return ref.current; | |
}, []) | |
} | |
function MyComponent() { | |
const ref = useRef(); | |
const [someUpdatingValue, setSomeUpdatingValue] = useState(0); | |
const getSomeUpdatingValue = usePullValue(someUpdatingValue); | |
useEffect(() => { | |
const el = ref.current; | |
const handler = () => { | |
const someUpdatingValue = getSomeUpdatingValue(); | |
// do something with _latest_ `someUpdatingValue` | |
}; | |
el.addEventListener('click', handler); | |
return () => { | |
el.removeEventListener('click', handler); | |
}; | |
}, [getSomeUpdatingValue]); | |
return <div ref={ref}>{/* blah */}</div>; | |
} | |
export default MyComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's also a simpler use case for
usePullValue
which is just removing reactivity of a dependency of an effect.