📖 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
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
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
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
Hint
Return a <div> element that displays Window width: {width}.
Practice
(1/5)
1. What is the main purpose of a cleanup function in a React useEffect hook?
easy
A. To initialize state variables before rendering
B. To remove timers, listeners, or subscriptions when the component unmounts or before the effect reruns
C. To fetch data from an API after the component mounts
D. To render JSX elements conditionally
Solution
Step 1: Understand the role of cleanup functions
Cleanup functions are used to tidy up side effects like timers or event listeners to prevent memory leaks.
Step 2: Identify when cleanup runs
Cleanup runs when a component unmounts or before the effect runs again, ensuring resources are freed.
Final Answer:
To remove timers, listeners, or subscriptions when the component unmounts or before the effect reruns -> Option B
Quick Check:
Cleanup function purpose = Remove resources [OK]
Hint: Cleanup frees resources when component unmounts or effect reruns [OK]
Common Mistakes:
Thinking cleanup initializes state
Confusing cleanup with data fetching
Assuming cleanup runs after every render
2. Which of the following is the correct syntax to define a cleanup function inside useEffect?
D. useEffect(() => { return clearTimeout(timer); }, []);
Solution
Step 1: Recognize cleanup function syntax
The cleanup function must be returned from the effect callback as a function.
Step 2: Check each option
useEffect(() => { return () => { clearTimeout(timer); }; }, []); correctly returns a function that calls clearTimeout. Others either don't return a function or return the wrong value.
A. The cleanup function should be a function returned, not the result of removeEventListener call
B. The event listener should be added inside the cleanup function
C. The effect should not have a dependency array
D. handleResize should be defined inside useEffect
Solution
Step 1: Check cleanup function syntax
The cleanup must be a function returned from useEffect, not the result of calling removeEventListener immediately.
Step 2: Identify correct cleanup pattern
The cleanup should be: return () => window.removeEventListener('resize', handleResize); to run on unmount.
Final Answer:
The cleanup function should be a function returned, not the result of removeEventListener call -> Option A
Quick Check:
Cleanup must be a returned function [OK]
Hint: Return a function for cleanup, not the cleanup call itself [OK]
Common Mistakes:
Calling cleanup immediately instead of returning a function
Adding event listener inside cleanup
Ignoring dependency array effects
5. You want to subscribe to a WebSocket in a React component and clean up properly. Which code correctly uses a cleanup function to close the socket when the component unmounts or the URL changes?
function SocketComponent({ url }) {
React.useEffect(() => {
const socket = new WebSocket(url);
socket.onmessage = (event) => console.log(event.data);
// What cleanup code is correct?
}, [url]);
return null;
}
hard
A. return () => { socket.close(); };
B. socket.close();
C. return socket.close();
D. return () => socket.onmessage = null;
Solution
Step 1: Understand cleanup for WebSocket
To avoid leaks, the socket must be closed when the component unmounts or URL changes.
Step 2: Identify correct cleanup syntax
The cleanup must be a function returned from useEffect that calls socket.close(). return () => { socket.close(); }; does this correctly.
Final Answer:
return () => { socket.close(); }; -> Option A
Quick Check:
Cleanup returns function closing socket [OK]
Hint: Return a function that closes socket for cleanup [OK]
Common Mistakes:
Calling close immediately instead of returning a function
Returning the result of close() instead of a function
Only nullifying event handlers without closing socket
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.