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!

3
  • 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. medium.com/wesionary-team/window-object-in-nextjs-1e505349c6f5 Commented Dec 6, 2021 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. Commented Dec 6, 2021 at 20:22
  • Does this answer your question? Window is not defined in Next.js React app Commented Dec 6, 2021 at 23:27

1 Answer 1

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 />}
  </>;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.