Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mahdiyazdani/402b871fb9f55f72e47d9b633ee5935c to your computer and use it in GitHub Desktop.
Save mahdiyazdani/402b871fb9f55f72e47d9b633ee5935c to your computer and use it in GitHub Desktop.
useWindowDimensions React Hook
import React from 'react';
import ReactDOM from 'react-dom';
function useWindowDimensions() {
const [width, setWidth] = React.useState(window.innerWidth);
const [height, setHeight] = React.useState(window.innerHeight);
React.useEffect(() => {
const handleResize = () => {
setWidth(window.innerWidth);
setHeight(window.innerHeight);
};
const resize = window.addEventListener('resize', handleResize);
return () => window.removeEventListener(resize, handleResize);
});
return {
width,
height,
};
}
function App() {
const { width, height } = useWindowDimensions();
return (
<div className="App">
<h2>width: {width}</h2>
<h2>height: {height}</h2>
<p>Resize the window.</p>
</div>
);
}
const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment