Skip to content

Instantly share code, notes, and snippets.

@Siemko
Created November 7, 2019 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Siemko/b31412fdfb9a1a9b8bf38e6a02d504eb to your computer and use it in GitHub Desktop.
Save Siemko/b31412fdfb9a1a9b8bf38e6a02d504eb to your computer and use it in GitHub Desktop.
import { useState, useEffect } from "react";
export default function useWindowSize() {
const [{width, height}, setSize] = useState({ window.innerWidth, window.innerHeight });
useEffect(() => {
const handleResize = () => setSize({ window.innerWidth, window.innerHeight });
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, [setSize]);
return {width, height}; // or: return [width, height]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment