Using Cleanup Function in React useEffect
📖 Scenario: You are building a React component that listens to window resize events to update the width shown on the screen. To avoid memory leaks, you need to clean up the event listener when the component unmounts.
🎯 Goal: Create a React functional component that tracks the window width using useState and useEffect. Add a cleanup function inside useEffect to remove the event listener when the component unmounts.
📋 What You'll Learn
Create a state variable called
width initialized to window.innerWidthCreate a
useEffect hook that adds a resize event listener to windowInside the event listener, update the
width state with the current window widthAdd a cleanup function inside
useEffect that removes the resize event listenerRender a
<div> that displays the current width💡 Why This Matters
🌍 Real World
Listening to window resize events is common in responsive web design to adjust layouts or content dynamically.
💼 Career
Understanding cleanup functions in useEffect is essential for React developers to prevent memory leaks and ensure app performance.
Progress0 / 4 steps