Created
May 11, 2020 16:45
-
-
Save polRk/aa515c04d31a4c743116119a85f51bf3 to your computer and use it in GitHub Desktop.
Watch component width changes
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 debounce from 'lodash/debounce' | |
import { RefObject, useEffect } from 'react' | |
export const useWidthObserver = <T extends HTMLElement>( | |
refObject: RefObject<T>, | |
setWidth: (width: number) => void | |
) => { | |
useEffect(() => { | |
function resizeListener() { | |
if (refObject.current) { | |
setWidth(refObject.current.clientWidth) | |
} | |
} | |
window.addEventListener('resize', debounce(resizeListener, 300)) | |
return () => window.removeEventListener('resize', resizeListener) | |
}, [refObject, setWidth]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment