Skip to content

Instantly share code, notes, and snippets.

@behagoras
Created December 24, 2020 18:24
Show Gist options
  • Save behagoras/17f1f898ff1ec877d14488005104f09f to your computer and use it in GitHub Desktop.
Save behagoras/17f1f898ff1ec877d14488005104f09f to your computer and use it in GitHub Desktop.
useWidthAndHeight.tsx
import { useRef, useState, useEffect } from 'react';
export default function useWidthAndHeight() {
const containerRef = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(0);
const getDimensions = () => {
if (containerRef.current) {
setWidth(containerRef.current.offsetWidth);
setHeight(containerRef.current.offsetHeight);
}
};
useEffect(() => {
const listener = () => getDimensions();
window.addEventListener('resize', listener);
return () => {
window.removeEventListener('resize', listener);
};
}, [containerRef]);
return [containerRef, width, height];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment