Created
January 24, 2019 13:01
-
-
Save stockulus/5ade186807ab6ad3ae11633a2c477daa 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 { 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