Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Window is undefined in Nextjs but values are needed in useState

Trying to get the exact window values as the screen size changes. How can i get the window values into useState()? Since useState cannot be used in a conditional, and window is undefined outside a useEffect?

    const isSSR = typeof window !== "undefined";
    const [windowSize, setWindowSize] = React.useState({
        width: isSSR ? 1200 : window.innerWidth,
        height: isSSR ? 800 : window.innerHeight,
    });

    function changeWindowSize() {
        setWindowSize({ width: window.innerWidth, height: window.innerHeight });
    }

    React.useEffect(() => {
        window.addEventListener("resize", changeWindowSize);

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

    return windowSize;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Two things to be corrected,

  1. Your isSSR logic is not right. due to that, window.innerWidth and window.innerHeight were evaluated in the server. It should be === not !==.
const isSSR = typeof window === "undefined";
  1. And change the client-side function to be safe like below.
function changeWindowSize() {
    if(!isSSR){
        setWindowSize({ width: window.innerWidth, height: window.innerHeight });
    }
}

*** changeWindowSize change is not needed since you call it only within a useEffect and useEffect hook is not executed in the server.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading