Skip to content

Instantly share code, notes, and snippets.

@polRk
Created May 11, 2020 16:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polRk/aa515c04d31a4c743116119a85f51bf3 to your computer and use it in GitHub Desktop.
Save polRk/aa515c04d31a4c743116119a85f51bf3 to your computer and use it in GitHub Desktop.
Watch component width changes
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