简体   繁体   中英

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM