Created
June 10, 2022 08:49
-
-
Save stekhn/b2f2b5ba4f6fe4f0766f6d3ae2df5a01 to your computer and use it in GitHub Desktop.
React hook for responsive width and height with support for resize events
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 { useState, useEffect } from 'react'; | |
const getDimensions = () => { | |
const { innerWidth: width, innerHeight: height } = window; | |
return { | |
width, | |
height | |
}; | |
}; | |
export const useDimensions = () => { | |
const [dimensions, setDimensions] = useState(getDimensions()); | |
useEffect(() => { | |
const handleResize = () => { | |
setDimensions(getDimensions()); | |
}; | |
window.addEventListener('resize', handleResize); | |
return () => window.removeEventListener('resize', handleResize); | |
}, []); | |
return dimensions; | |
}; | |
// Usage | |
// const { width } = useDimensions(); | |
// useEffect(() => { | |
// setWidth(width) | |
// }, [width]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment