score:2

Accepted answer

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

score: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
    }
}, [])

Related Query

More Query from same tag