Last active
January 17, 2021 14:34
-
-
Save vzaidman/c62869e8d3bdf9f67b8e72349bfa1691 to your computer and use it in GitHub Desktop.
useStateRef
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 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