1

I have a next problem:

I want to track some of field of undefined variable window, but which will be defined in future.

For example, if the inner field of variable window will be changed, I want to do some code.

useEffect(() => {
    if (window && window.innerWidth) {
        // Do something
    }
}, [window.innerWidth])

But next.js and react writes following:

enter image description here

How to achieve this effect? Thanks for any advice.

Boris Lebedev
  • 143
  • 2
  • 10
  • Maybe this could help => https://stackoverflow.com/questions/55151041/window-is-not-defined-in-next-js-react-app – Appy Mango Jan 21 '21 at 13:42

2 Answers2

2

This solution will work for your use case.

So we have 2 useEffect hooks.

The first useEffect attached an event listener to the window object. Because the window is used in a useEffect hook, it won't be executed on the server-side.

The second useEffect hook will listen to the state changes on innerWidth, which is being updated whenever the resize event happens.

  const [innerWidth, setInnerWidth] = useState<number | undefined>();

  useEffect(() => {
    // Handler to call on window resize
    function handleResize() {
      setInnerWidth(window.innerWidth);
    }

    // Add event listener
    window.addEventListener('resize', handleResize);
    // Call handler right away so state gets updated with initial window size
    handleResize();
    return () => window.removeEventListener('resize', handleResize);
  }, []); 

  useEffect(() => {
    // Handle your changes
    console.log(innerWidth);
  }, [innerWidth]);

  

Inspired by this useWindowResize implementation

Andrew Zheng
  • 2,612
  • 1
  • 20
  • 25
0

You can try using process.browser to just execute your command during rendering on the client side only.

   if (typeof window !== "undefined") { //client side code } 

/*OR TRY THIS */
/*Remove dependency array*/
useEffect(() => {
    if (window && window.innerWidth) {
        // Do something
    }
}, [])
Appy Mango
  • 1,298
  • 5
  • 16