Skip to content

Instantly share code, notes, and snippets.

@Bolza
Created April 9, 2020 14:33
Show Gist options
  • Save Bolza/533fd35ac07907a229ffbfadf267cc0b to your computer and use it in GitHub Desktop.
Save Bolza/533fd35ac07907a229ffbfadf267cc0b to your computer and use it in GitHub Desktop.
import React, { useRef, useEffect, useState } from 'react'
const useWindowSize = () => {
function getSize() {
return {
width: window.innerWidth,
height: window.innerHeight,
}
}
const [windowSize, setWindowSize] = useState(getSize)
useEffect(() => {
function handleResize() {
setWindowSize(getSize())
}
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, []) // Empty array ensures that effect is only run on mount and unmount
return windowSize
}
export default useWindowSize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment