Last active
December 22, 2023 17:13
-
-
Save vzaidman/53f0f526962ce4dac2e99a4f1c1ce038 to your computer and use it in GitHub Desktop.
useRefWithCallback
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
// the hook | |
function useRefWithCallback(onMount, onUnmount) { | |
const nodeRef = useRef(null); | |
const setRef = useCallback(node => { | |
if (nodeRef.current) { | |
onUnmount(nodeRef.current); | |
} | |
nodeRef.current = node; | |
if (nodeRef.current) { | |
onMount(nodeRef.current); | |
} | |
}, [onMount, onUnmount]); | |
return setRef; | |
} | |
const onMouseDown = useCallback(e => console.log('hi!', e.target.clientHeight), []); | |
const setDivRef = useRefWithCallback( | |
node => node.addEventListener("mousedown", onMouseDown), | |
node => node.removeEventListener("mousedown", onMouseDown) | |
); | |
// <div ref={setDivRef} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment