Skip to content

Instantly share code, notes, and snippets.

@0xLDev
Created December 18, 2021 08:46
Show Gist options
  • Save 0xLDev/4c4986247be6f898c269a60292d9c4d6 to your computer and use it in GitHub Desktop.
Save 0xLDev/4c4986247be6f898c269a60292d9c4d6 to your computer and use it in GitHub Desktop.
import { useCallback, useEffect, useState } from 'react';
import { useEventListener } from 'useEventListener';
const DEFAULT_SIZE = {
width: 0,
height: 0,
};
export const useElementSize = (elementRef) => {
const [size, setSize] = useState(DEFAULT_SIZE);
const updateElementSize = useCallback(() => {
const node = elementRef.current;
if (node) {
const { width, height } = node.getBoundingClientRect();
setSize({ width, height });
}
}, [elementRef]);
useEffect(() => {
updateElementSize();
}, [updateElementSize]);
useEventListener('resize', updateElementSize);
return size;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment