Creating a useDimensions Hook


The visualization component is going to be wrapped in a responsive div. We need a way to retrieve this container's dimensions.

To achieve this, let's create a hook called useDimensions.

Free
4 minutes read

What is a hook

A hook is a special function that lets you use state and other React features in functional components, as explained in the documentation.

That's exactly what we need! A function that we can reuse in all our chart components and that manages its internal state.

🎣 Hook to get the container dimensions

That's how the hook looks like:

import { useEffect, useLayoutEffect, useState } from "react";

// Hook to retrieve the dimensions of a div.
// react-graph-gallery.com
export const useDimensions = (targetRef: React.RefObject<HTMLDivElement>) => {

  const getDimensions = () => {
    return {
      width: targetRef.current ? targetRef.current.offsetWidth : 0,
      height: targetRef.current ? targetRef.current.offsetHeight : 0
    };
  };

  const [dimensions, setDimensions] = useState(getDimensions);

  const handleResize = () => {
    setDimensions(getDimensions());
  };

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

  useLayoutEffect(() => {
    handleResize();
  }, []);

  return dimensions;
}

This hook is essentially a function that checks the offsetWidth and offsetHeight of a provided ref.


An event listener for the resize event is added to the window to ensure the dimensions are updated when the window size changes.

I do not want to go too much in depth on how it works. More importantly, let's see how to use it!