Ahmed Elhoseny
Ahmed Elhoseny

Reputation: 131

Why do I need cleanup in useEffect in react

Im new to react and Im not sure why do we need a cleanup function when dealing with EventListeners, Iam trying to set an event when resizing my window but i only have 1 event in (Elements -> Event Listeners) tab in chrome dev tools, even if I don't return a cleanup function in my hook

Heres my code:

 useEffect(() => {
    window.addEventListener("resize", function checksize() {
      console.log("1");
    });
  });

Upvotes: 2

Views: 567

Answers (2)

lanxion
lanxion

Reputation: 1430

First of all, you should absolutely avoid using that in your code, because on each rerender, it is going to add a new event listener to the window.

Secondly, to answer your question, you should have a cleanup effect to remove event listeners and other similar mechanisms to avoid memory leaks. If you don't clean them up, then you leave dangling eventlisteners taking up memory which is not a good idea, and may be picked up on within your other components as well. So the ideal way to handle this kind of code is

 const logOne = () => console.log("1"); //put the function reference in a variable so that you can remove the event afterwards

 useEffect(() => {
    window.addEventListener("resize", logOne);

   return () => {
     window.removeEventListener("resize", logOne); //remove event listener on unmount
   }
  }, []); //empty dependency array so that function only runs on first render, so that consequent rerenders don't cause you to add more of these event listeners

Upvotes: 5

zero298
zero298

Reputation: 26930

Because you will keep adding listeners every render. Instead of printing "1" once, it will print it twice next time. Then 3 times on the next re-render and so on.

Upvotes: 1

Related Questions