← Back to all snippets
JAVASCRIPT

Custom useElementDimensions Hook for Tracking DOM Element Size

A React hook that provides dynamic dimensions (width, height, position) of a specified DOM element, useful for responsive layouts and animations.

import { useState, useEffect, useRef } from 'react';

const useElementDimensions = () => {
  const ref = useRef(null);
  const [dimensions, setDimensions] = useState({
    width: 0,
    height: 0,
    x: 0,
    y: 0,
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  });

  useEffect(() => {
    const updateDimensions = () => {
      if (ref.current) {
        const { width, height, x, y, top, left, right, bottom } = ref.current.getBoundingClientRect();
        setDimensions({ width, height, x, y, top, left, right, bottom });
      }
    };

    // Initial dimensions
    updateDimensions();

    // Setup ResizeObserver if available
    if (typeof ResizeObserver !== 'undefined') {
      const observer = new ResizeObserver(entries => {
        // Only re-measure if the observed element is the one we care about
        if (entries[0] && entries[0].target === ref.current) {
          updateDimensions();
        }
      });
      if (ref.current) {
        observer.observe(ref.current);
      }
      return () => {
        if (ref.current) { // Ensure ref.current is still available during cleanup
          observer.unobserve(ref.current);
        }
        observer.disconnect();
      };
    } else {
      // Fallback for older browsers (less efficient)
      window.addEventListener('resize', updateDimensions);
      return () => {
        window.removeEventListener('resize', updateDimensions);
      };
    }
  }, []); // Empty dependency array ensures this runs once on mount

  return [ref, dimensions];
};

export default useElementDimensions;

// How to use:
// import useElementDimensions from './useElementDimensions';
// function MyResizableComponent() {
//   const [myRef, dimensions] = useElementDimensions();
//   return (
//     <div ref={myRef} style={{ border: '1px solid red', padding: '10px' }}>
//       <p>Width: {dimensions.width.toFixed(2)}px</p>
//       <p>Height: {dimensions.height.toFixed(2)}px</p>
//       <p>Top: {dimensions.top.toFixed(2)}px</p>
//       <p>Left: {dimensions.left.toFixed(2)}px</p>
//     </div>
//   );
// }
How it works: This hook provides a way to get the real-time dimensions and position of any DOM element. It uses `useRef` to create a reference that can be attached to an element. `useEffect` then initializes the dimensions and sets up an observer. If `ResizeObserver` is available, it's used for efficient updates whenever the element's size changes. Otherwise, it falls back to listening for the global 'resize' event. The hook returns both the ref to attach to your element and the `dimensions` object, allowing components to react dynamically to layout changes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs