1

I have a function component in react... so it redraws when parent data changes.

Inside the component i have this

    const num = Math.floor((Math.random() * 100) + 1);
    console.log("set num", num);
    window.removeEventListener("resize", function(){});
    window.addEventListener('resize', function(){
        console.log(num);
    })

This is just to illustrate the problem, but... it creates a new window resize event every time the component redraws... why? And, how do I stop it?

Nathan Leggatt
  • 398
  • 1
  • 6
  • 18
  • Not sure if this is related to a different question but maybe this one helps: https://stackoverflow.com/questions/58942210/how-to-get-size-of-an-element-in-an-react-app-that-is-totally-based-on-functiona – norbitrial May 07 '20 at 18:00
  • Where and how do you use the above code? – Shubham Khatri May 07 '20 at 18:01
  • 1
    You probably need to place these event listeners inside an useEffect hook for your functional component. That way you control the number of times you want these listeners to attach and detach. Since I think it’s a one time thing. Pass them in an useEffect with empty dependency array. – Lakshya Thakur May 07 '20 at 18:04

0 Answers0