0
0
Reactframework~30 mins

Cleanup function in React - Mini Project: Build & Apply

Choose your learning style9 modes available
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.innerWidth
Create a useEffect hook that adds a resize event listener to window
Inside the event listener, update the width state with the current window width
Add a cleanup function inside useEffect that removes the resize event listener
Render 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
1
Setup state to track window width
Create a React functional component called WindowWidth. Inside it, use useState to create a state variable called width initialized to window.innerWidth.
React
Need a hint?

Use const [width, setWidth] = useState(window.innerWidth); inside the component.

2
Add useEffect to listen to window resize
Inside the WindowWidth component, add a useEffect hook. Inside it, define a function called handleResize that updates width state using setWidth(window.innerWidth). Then add a resize event listener on window that calls handleResize.
React
Need a hint?

Inside useEffect, define handleResize and add the event listener.

3
Add cleanup function to remove event listener
Inside the useEffect hook, add a cleanup function that removes the resize event listener from window using window.removeEventListener('resize', handleResize).
React
Need a hint?

Return a function inside useEffect that calls window.removeEventListener('resize', handleResize).

4
Render the current window width
Inside the WindowWidth component, add a return statement that renders a <div> showing the text Window width: followed by the current width state.
React
Need a hint?

Return a <div> element that displays Window width: {width}.