Home > database >  Why resized function is always trigger when resizing browser window. even if there is no dependency
Why resized function is always trigger when resizing browser window. even if there is no dependency

Time:09-05

 const [innerWidth, setInnerWidth] = useState(window.innerWidth)


function resized () {
    
    setInner(window.innerWidth)
  }

 useEffect(()=>{
    
    window.addEventListener('resize', resized)

    return () => {
      
      window.removeEventListener('resize', resized)
    }
 }, [])
There is no dependency set in useEffect, meaning useEffcet only triggers when page load. Resized function is inside the useEffect and it's only triggered when the page load. But this function has always trigger when we resized the browser window it supposes to be triggered only once.

CodePudding user response:

window.addEventListener('resize', resized)

When you run this line of code, you are asking the browser to call resized every time there is a resize event. The empty dependency array only controls how often the useEffect runs, ie, how often you add and remove the event listener. But if you've added the listener, even once, you will then get an unlimited number of resize events from the browser.

If you only want to pay attention to the first time the event happens, you will need to add some code to remove the listener once it goes off once:

useEffect(() => {
  function resized () {    
    setInner(window.innerWidth)
    window.removeEventListener('resize', resized); // <---- added
  }
  window.addEventListener('resize', resized)

  return () => {      
    window.removeEventListener('resize', resized)
  }
}, []);

CodePudding user response:

Try this

const [innerWidth, setInnerWidth] = useState(window.innerWidth);

function resized() {
    setInner(window.innerWidth);
    window.removeEventListener("resize", resized);
}

useEffect(() => {
    window.addEventListener("resize", resized);
}, []);
  • Related