Created
November 5, 2024 03:16
-
-
Save Soumyarian98/8c84fe82615c38940700adaaaaaf2ef5 to your computer and use it in GitHub Desktop.
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
| import { useEffect, useRef, useState } from "react"; | |
| const useMeasure = () => { | |
| const ref = useRef<HTMLDivElement>(null); | |
| const [bounds, set] = useState({ left: 0, top: 0, width: 0, height: 0 }); | |
| const [ro] = useState( | |
| () => new ResizeObserver(([entry]) => set(entry.contentRect)) | |
| ); | |
| useEffect(() => { | |
| if (ref.current) ro.observe(ref.current); | |
| return () => ro.disconnect(); | |
| }, [ro]); | |
| return [ref, bounds] as const; | |
| }; | |
| export default useMeasure; |
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
| import { useEffect, useRef, useState } from "react"; | |
| const useMeasure = () => { | |
| const ref = useRef<HTMLElement | null>(null); | |
| const [bounds, setBounds] = useState<DOMRect>({ | |
| x: 0, | |
| y: 0, | |
| width: 0, | |
| height: 0, | |
| top: 0, | |
| left: 0, | |
| bottom: 0, | |
| right: 0, | |
| toJSON: () => {}, | |
| }); | |
| useEffect(() => { | |
| if (!ref.current) return; | |
| let animationFrameId: number; | |
| const observer = new ResizeObserver(([entry]) => { | |
| // Use `requestAnimationFrame` to prevent layout thrashing | |
| animationFrameId = requestAnimationFrame(() => { | |
| if (entry) setBounds(entry.contentRect); | |
| }); | |
| }); | |
| observer.observe(ref.current); | |
| return () => { | |
| cancelAnimationFrame(animationFrameId); | |
| observer.disconnect(); | |
| }; | |
| }, []); | |
| return [ref, bounds] as const; | |
| }; | |
| export default useMeasure; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment