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 :
Two things to be corrected,
- Your
isSSRlogic is not right. due to that,window.innerWidthandwindow.innerHeightwere evaluated in the server. It should be===not!==.
const isSSR = typeof window === "undefined";
- 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.