0

At first, it was working as intended. I don't know what happened, but it randomly started throwing an error "ReferenceError: window is not defined". I am using Next.js and the code that's causing the error is in a custom react hook.

useWindowDimensions.js

import { useState, useEffect } from 'react';

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height,
  };
}

export default function useWindowDimensions() {
  const [windowDimensions, setWindowDimensions] = useState(
    getWindowDimensions()
  );

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

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

  return windowDimensions;
}

Footer.js

import useWindowDimensions from '../hooks/useWindowDimensions';

const Footer = () => {
  // detect the screen resolution

  const { height, width } = useWindowDimensions();
...

Any help would be appreciated. Thanks!

ricemilk
  • 85
  • 1
  • 6
  • Are you using server-side rendering? If so, window doesn't exist on the server side, and you'll need to check for `window` before using it. https://medium.com/wesionary-team/window-object-in-nextjs-1e505349c6f5 – xdumaine Dec 06 '21 at 19:32
  • @xdumaine Yes, I'm using ssr, and thanks for the article. I tried the 2. and 3. fix, but they didn't work, but I'm not sure how to implement the 1. fix. I later have some conditional rendering with the width data. The other fixes returned me an error `TypeError: Cannot destructure property 'width' of '(0 , _hooks_useWindowDimensions__WEBPACK_IMPORTED_MODULE_3__.default)(...)' as it is undefined.` – ricemilk Dec 06 '21 at 20:22
  • Does this answer your question? [Window is not defined in Next.js React app](https://stackoverflow.com/questions/55151041/window-is-not-defined-in-next-js-react-app) – juliomalves Dec 06 '21 at 23:27

1 Answers1

2

Render Footer as dynamic in the parent component.

import dynamic from 'next/dynamic';

// import { Footer } from 'components';
const Footer = dynamic(() => import('components/Footer'), { ssr: false });

or

const SomeParent = () => {
  return <>
    {!loading && <Footer />}
  </>;
}
CrowRish
  • 174
  • 6