Skip to content

Instantly share code, notes, and snippets.

@marcovincit
Created July 14, 2021 23:00
Show Gist options
  • Select an option

  • Save marcovincit/6dfaabbd1938571f4cad4934e534b565 to your computer and use it in GitHub Desktop.

Select an option

Save marcovincit/6dfaabbd1938571f4cad4934e534b565 to your computer and use it in GitHub Desktop.

Revisions

  1. marcovincit created this gist Jul 14, 2021.
    21 changes: 21 additions & 0 deletions useWindowSize.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    import { useEffect, useState } from "react";

    export default function useWindowSize() {
    const [windowWidth, setWindowWidth] = useState(0);
    const [windowHeight, setWindowHeight] = useState(0);

    useEffect(() => {
    function updateSize() {
    setWindowWidth(window.innerWidth);
    setWindowHeight(window.innerHeight);
    }

    window.addEventListener("resize", updateSize);

    updateSize();

    return () => window.removeEventListener("resize", updateSize);
    }, []);

    return { windowWidth, windowHeight };
    }