Skip to content

Instantly share code, notes, and snippets.

@GitSquared
Created March 14, 2022 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GitSquared/0cb2881ded018a0da23a0a92b59f5d65 to your computer and use it in GitHub Desktop.
Save GitSquared/0cb2881ded018a0da23a0a92b59f5d65 to your computer and use it in GitHub Desktop.
import { RefObject, useState, useEffect } from "react";
type DimensionsTuple = [number, number]; // width, height
export function useResponsiveDimensions(
ref: RefObject<HTMLDivElement>
): DimensionsTuple {
const [dimensions, setDimensions] = useState<DimensionsTuple>([500, 300]);
useEffect(() => {
if (!ref.current) return;
const element = ref.current;
const updateDimensions = () => {
const { width, height } = element.getBoundingClientRect();
setDimensions([width, height]);
};
updateDimensions();
const observer = new ResizeObserver(updateDimensions);
observer.observe(element);
return () => {
observer.disconnect();
};
}, [ref]);
return dimensions;
}
@GitSquared
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment