Fix the React useEffect Cleanup
HardChallenge 16 of 20
Fix the React useEffect Cleanup
HardThis React component sets up an event listener but has a memory leak. Fix the implementation to properly clean up resources.
Challenge 16 of 20
80 XP
Community Solutions
ReactHooksuseEffectCleanupJavaScript
Exit ChallengeTest Cases
0/1 passingTest Case #1
Input: Mount and unmount the component
Expected: No memory leaks or console warnings
Run tests to see results
solution.js
1
<span class="token keyword">import</span> React, { useState, useEffect } from <span <span class="token keyword">class</span>="token number">039</span>;react<span <span class="token keyword">class</span>="token number">039</span>;;
<span class="token keyword">function</span> WindowResizeTracker() {
<span class="token keyword">const</span> [windowWidth, setWindowWidth] = useState(window.innerWidth);
useEffect(() => {
<span class="token keyword">function</span> handleResize() {
setWindowWidth(window.innerWidth);
}
window.addEventListener(<span <span class="token keyword">class</span>="token number">039</span>;resize<span <span class="token keyword">class</span>="token number">039</span>;, handleResize);
<span <span class="token keyword">class</span>=<span <span class="token keyword">class</span>="token string">"token comment"</span>>// Missing cleanup</span>
}, []);
<span class="token keyword">return</span> (
<div>
<p>Current window width: {windowWidth}px</p>
</div>
);
}
<span class="token keyword">export</span> default WindowResizeTracker;Console
Run your code to see output here