Skip to content

Instantly share code, notes, and snippets.

@wolfcoder
Created October 22, 2024 07:50
Show Gist options
  • Save wolfcoder/83989262f4d14d0cd4ae62d9a048839a to your computer and use it in GitHub Desktop.
Save wolfcoder/83989262f4d14d0cd4ae62d9a048839a to your computer and use it in GitHub Desktop.
React Hook Use Window Width
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