Created
November 16, 2019 21:10
-
-
Save geddski/603765ef49d8091b673dbd1deab7e121 to your computer and use it in GitHub Desktop.
hook for calculating a component's bounding rect
This file contains 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, { useState, useEffect, useLayoutEffect, useContext } from 'react'; | |
import debounce from "debounce"; | |
function useComponentRect(containerRef, debounceTime = 100) { | |
const [rect, setRect] = useState(); | |
const calculateRect = debounce(() => { | |
if (containerRef.current){ | |
const rect = containerRef.current.getBoundingClientRect(); | |
setRect(rect); | |
} | |
}, debounceTime); | |
// calculate on first render | |
// once all web fonts have all loaded | |
useLayoutEffect(() => { | |
document.fonts.ready.then(() => { | |
calculateRect(); | |
}); | |
}, []); | |
useEffect(() => { | |
window.addEventListener("resize", calculateRect); | |
return () => { | |
window.removeEventListener("resize", calculateRect); | |
} | |
}, []); | |
return rect; | |
} | |
export default useComponentRect; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment