Skip to content

Instantly share code, notes, and snippets.

@chriskavanagh
Created November 28, 2019 23:52
Show Gist options
  • Save chriskavanagh/f05528c9737ebad90b00e4f4802676a9 to your computer and use it in GitHub Desktop.
Save chriskavanagh/f05528c9737ebad90b00e4f4802676a9 to your computer and use it in GitHub Desktop.
function App() {
const size = useWindowSize();
return (
<div>
{size.width}px / {size.height}px
</div>
);
}
// Hook
function useWindowSize() {
const isClient = typeof window === "object";
function getSize() {
return {
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined
};
}
const [windowSize, setWindowSize] = useState(getSize);
useEffect(() => {
if (!isClient) {
return false;
}
function handleResize() {
setWindowSize(getSize());
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []); // Empty array ensures that effect is only run on mount and unmount
return windowSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment