Skip to content

Instantly share code, notes, and snippets.

@vzaidman
Last active January 17, 2021 14:34
Show Gist options
  • Save vzaidman/c62869e8d3bdf9f67b8e72349bfa1691 to your computer and use it in GitHub Desktop.
Save vzaidman/c62869e8d3bdf9f67b8e72349bfa1691 to your computer and use it in GitHub Desktop.
useStateRef
// the hook
function useStateRef(processNode) {
const [node, setNode] = useState(null);
const setRef = useCallback(newNode => {
setNode(processNode(newNode));
}, [processNode]);
return [node, setRef];
}
// how it's used
const [clientHeight, setRef] = useStateRef(node => (node?.clientHeight || 0));
useEffect(() => {
console.log(`the new clientHeight is: ${clientHeight}`);
}, [clientHeight])
// <div ref={setRef}....
// <div>the current height is: {clientHeight}</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment