简体   繁体   中英

How to track value of undefined variable in dependency list in useEffect in React and Next.js

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:

在此处输入图像描述

How to achieve this effect? Thanks for any advice.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM