Created
October 22, 2024 07:50
-
-
Save wolfcoder/83989262f4d14d0cd4ae62d9a048839a to your computer and use it in GitHub Desktop.
React Hook Use Window Width
This file contains 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 useWindowWidth = () => { | |
const [windowWidth, setWindowWidth] = useState(window.innerWidth); | |
useEffect(() => { | |
const handleResize = () => { | |
setWindowWidth(window.innerWidth); | |
}; | |
window.addEventListener('resize', handleResize); | |
// Cleanup event listener on component unmount | |
return () => { | |
window.removeEventListener('resize', handleResize); | |
}; | |
}, []); | |
return windowWidth; | |
}; | |
export default useWindowWidth; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment