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
.
Wip
4 minutes readWhat 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.
Explain more why a hook is what we need.
🎣 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.
Why do I have the useLayoutEffect in there?
Explain more in depth how it works.