Skip to content

Instantly share code, notes, and snippets.

@vzaidman
Last active December 22, 2023 17:13
Show Gist options
  • Save vzaidman/53f0f526962ce4dac2e99a4f1c1ce038 to your computer and use it in GitHub Desktop.
Save vzaidman/53f0f526962ce4dac2e99a4f1c1ce038 to your computer and use it in GitHub Desktop.
useRefWithCallback
// 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