useElementSize

A React hook that tracks element dimensions in real-time using ResizeObserver. Perfect for responsive layouts, dynamic content sizing, and custom resize functionality. Provides accurate width and height measurements with TypeScript support.

Interactive Demo

This card's dimensions are being tracked in real-time.

Width: 0px

Height: 0px

Implementation

export function useElementSize<T extends HTMLElement = HTMLElement>(ref: RefObject<T | null>) {
  const [size, setSize] = useState<{ width: number; height: number }>({
    width: 0,
    height: 0,
  });

  useEffect(() => {
    const element = ref?.current;
    if (!element) return;

    const observer = new ResizeObserver((entries) => {
      const { width, height } = entries[0].contentRect;
      setSize({ width, height });
    });

    observer.observe(element);

    return () => {
      observer.disconnect();
    };
  }, [ref]);

  return size;
}

Usage Examples

import { useElementSize } from '@/components/hooks/useElementSize';

function ResizableComponent() {
  const ref = useRef<HTMLDivElement>(null);
  const { width, height } = useElementSize(ref);
  
  return (
    <div ref={ref} className="resize-x overflow-auto p-4 border">
      <p>Width: {width}px</p>
      <p>Height: {height}px</p>
    </div>
  );
}

Documentation

Key Features

  • Real-time size tracking using ResizeObserver
  • TypeScript support with proper element typing
  • Automatic cleanup of observers
  • Zero dependencies
  • SSR compatible
  • Memory efficient with single observer pattern

Common Use Cases

  • Responsive layouts based on element dimensions
  • Dynamic content sizing
  • Custom resize handles
  • Virtualized lists
  • Canvas sizing

API Reference

useElementSize<T extends HTMLElement>(ref: RefObject<T>): { width: number; height: number }

Returns the current dimensions of the referenced element.

Parameters:

  • ref: React ref object pointing to the target element

Returns:

  • An object containing width and height in pixels

Browser Compatibility

The hook uses the ResizeObserver API, which is supported in all modern browsers. For older browsers, consider using a polyfill. Check browser compatibility for more details.