ricemilk
ricemilk

Reputation: 85

Getting an error: "ReferenceError: window is not defined"

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!

Upvotes: 0

Views: 1794

Answers (1)

CrowRish
CrowRish

Reputation: 171

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

Upvotes: 2

Related Questions