observer div element size/dimensions using useRef and window resize event (React Hook)

Viewed 3949

I am trying to constantly observe/detect a div element size using React Hook JS. I have used different ways but every time I see a common issue where decreasing window size doesn't change the ref.current.offsetWidth but increasing it, will change ref.current.offsetWidth value.

Here is my code:

function Chart({}) {
    const targetRef = useRef(null);
    const [dimensions, setDimensions] = useState({width: 0, height: 0});

    const updateDimensions = debounce(() => {
        if(targetRef.current) {
            setDimensions({
                width: targetRef.current.offsetWidth,
                height: targetRef.current.offsetHeight
            });
        }
    }, 50);

    useEffect(() => {
        updateDimensions();
    }, []);

    useEffect(() => {
        window.addEventListener("resize", updateDimensions);
        updateDimensions();
        return () => {
            window.removeEventListener("resize", updateDimensions);
        };
    }, []);

    return (
        <div style={{minHeight: 250}} ref={targetRef}>
           <some svg component/>
        </div>

    );
}

Note: Re-rendering the entire app will update the dimensions, but I don't want to refresh the whole page to get the right size.

1 Answers
Related