React useEffect Cleanup: Preventing Memory Leaks and Improving Performance

Today I learned how useEffect cleanup actually works in React — and it completely changed how I think about side effects. When we use useEffect, it runs after render. But what many beginners ignore is the cleanup function. Why is cleanup important? Prevents memory leaks Stops unnecessary API calls Removes event listeners properly Clears intervals and timeouts Example: When you add an event listener inside useEffect, you must remove it when the component unmounts. Otherwise, it keeps running in the background. That’s where cleanup comes in. useEffect(() => { const handleResize = () => console.log("Resized"); window.addEventListener("resize", handleResize); return () => { window.removeEventListener("resize", handleResize); }; }, []); The function returned inside useEffect runs: Before the next effect runs When the component unmounts Small detail. Big difference in performance. React is simple — until you understand the details. #ReactJS #FrontendDeveloper #JavaScript #WebDevelopment #LearningInPublic #100DaysOfCode

To view or add a comment, sign in

Explore content categories