0

I keep getting this error ReferenceError: window is not defined when deploying to Vercel and I don't have the same error on localhost.

What am I doing wrong in the code below?

export function WindowContextProvider({ children }: WindowContextProviderProps): JSX.Element {
  const [windowSize, setWindowSize] = useState<WindowSize>({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() => {
    const handleResize = (): void =>
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });

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

  const value: WindowContext = {
    ...windowSize,
    isMobile: windowSize.width < 500,
  };

  return <WindowContext.Provider value={value}>{children}</WindowContext.Provider>;
}
Mintee
  • 505
  • 4
  • 22
  • 1
    I'm assuming you're using Next.js, in which case: Next.js tries to pre-render your code on the server, where the `window` variable doesn't exist, so you'll have to make sure you only use it in client side code - you can do that by checking if the variable is `undefined` first and if it isn't, then you can go ahead and use it. I think locally Next.js doesn't do pre-rendering and that's why it works there. Try changing your code to this: https://pastebin.com/DNx8v13y (also see: https://stackoverflow.com/questions/55151041/window-is-not-defined-in-next-js-react-app) – richardszegh Dec 10 '22 at 21:47

1 Answers1

0

Changing my code to this fixed the error:

export function WindowContextProvider({ children }: WindowContextProviderProps): JSX.Element {
  const [windowSize, setWindowSize] = useState<WindowSize>({
    width: 0,
    height: 0,
  });
 
  useEffect(() => {
    // if (typeof window === undefined) {
    //     return;
    // }
 
    setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight
    });
 
    const handleResize = (): void =>
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
 
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
 
  const value: WindowContext = {
    ...windowSize,
    isMobile: windowSize.width < 500,
  };
 
  return <WindowContext.Provider value={value}>{children}</WindowContext.Provider>;
}
Mintee
  • 505
  • 4
  • 22
  • 2
    You don't need to check if `window` is `undefined` on `useEffect` since it only runs client-side, so `window` will be available. – ivanatias Dec 10 '22 at 22:15