Skip to content
This repository has been archived by the owner on Apr 25, 2024. It is now read-only.

Commit

Permalink
window dimension hook cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
andreiggr committed Nov 5, 2021
1 parent 7b2f299 commit 6f94af1
Showing 1 changed file with 1 addition and 8 deletions.
9 changes: 1 addition & 8 deletions src/helpers/useWindowSize.jsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,28 @@
import { useState, useEffect } from 'react';

export default function useWindowSize() {
// Initialize state with undefined width/height so server and client renders match
// Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
if (typeof window !== 'undefined') {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
}
// Add event listener
if (typeof window !== 'undefined') {
window.addEventListener('resize', handleResize);
handleResize();
}
// Call handler right away so state gets updated with initial window size
// Remove event listener on cleanup
return () => {
if (typeof window !== 'undefined') {
window.removeEventListener('resize', handleResize);
}
};
}, []); // Empty array ensures that effect is only run on mount
}, []);
return windowSize;
}

0 comments on commit 6f94af1

Please sign in to comment.