useElementSize

Hook to get the real-time width and height of any DOM element.


✅ Features

  • Uses ResizeObserver internally
  • Responds to dynamic content and layout changes
  • Works with any valid DOM ref

📦 Usage

1import { useElementSize } from './useElementSize';
2
3const ref = useRef(null);
4const { width, height } = useElementSize(ref);
5
6return (
7  <div ref={ref}>
8    Width: {width}px, Height: {height}px
9  </div>
10);

📋 Source Code

This is the full implementation of useElementSize

1import { useState, useLayoutEffect, RefObject } from 'react';
2
3export function useElementSize(ref: RefObject<HTMLElement>) {
4  const [size, setSize] = useState({ width: 0, height: 0 });
5
6  useLayoutEffect(() => {
7    const element = ref.current;
8    if (!element) return;
9
10    const observer = new ResizeObserver(([entry]) => {
11      const { width, height } = entry.contentRect;
12      setSize({ width, height });
13    });
14
15    observer.observe(element);
16    return () => observer.disconnect();
17  }, [ref]);
18
19  return size;
20}
21