Skip to content

Instantly share code, notes, and snippets.

@stockulus
Created January 24, 2019 13:01
Show Gist options
  • Save stockulus/5ade186807ab6ad3ae11633a2c477daa to your computer and use it in GitHub Desktop.
Save stockulus/5ade186807ab6ad3ae11633a2c477daa to your computer and use it in GitHub Desktop.
import { useEffect, useState } from 'react'
export const useClientRect = ref => {
const getClientRect = () => {
if (!ref || !ref.current) return null
const clientRects = ref.current.getClientRects()
return clientRects.length > 0 ? clientRects[0] : null
}
const [state, setState] = useState(getClientRect())
const updateState = () => setState(getClientRect())
useEffect(() => {
updateState()
window.addEventListener('resize', updateState)
return () => window.removeEventListener('resize', updateState)
}, [ref.current])
return state
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment