Complete the code to run cleanup when the component unmounts.
useEffect(() => {
return () => {
[1];
};
}, []);The cleanup function inside useEffect runs when the component unmounts. Logging 'Cleanup' shows this behavior.
Complete the code to clean up an event listener on unmount.
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => {
window.[1]('resize', handleResize);
};
}, []);To avoid memory leaks, remove event listeners in the cleanup function using removeEventListener.
Fix the error in the cleanup function to avoid memory leaks.
useEffect(() => {
const timer = setTimeout(() => {
console.log('Timer done');
}, 1000);
return () => {
clearTimeout([1]);
};
}, []);The timer ID returned by setTimeout must be cleared with clearTimeout using the same variable timer.
Fill both blanks to properly clean up a subscription on unmount.
useEffect(() => {
const subscription = api.subscribe(data => setData(data));
return () => {
subscription.[1]();
console.[2]('Unsubscribed');
};
}, []);Call unsubscribe to stop the subscription and log a message with console.log during cleanup.
Fill all three blanks to clean up a WebSocket connection on unmount.
useEffect(() => {
const socket = new WebSocket('wss://example.com');
socket.onmessage = event => setMessage(event.data);
return () => {
socket.[1]();
socket.[2] = null;
console.[3]('WebSocket closed');
};
}, []);Call close() to close the WebSocket, set onmessage to null to remove the handler, and log a message with console.log.