Created
December 18, 2021 08:46
-
-
Save 0xLDev/4c4986247be6f898c269a60292d9c4d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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