Complete the code to add a cleanup function inside useEffect.
useEffect(() => {
const timer = setTimeout(() => {
console.log('Hello');
}, 1000);
return [1];
}, []);The cleanup function must be a function that clears the timeout using clearTimeout(timer). So we return a function () => clearTimeout(timer).
Complete the code to clean up an event listener in useEffect.
useEffect(() => {
function onResize() {
console.log('Resized');
}
window.addEventListener('resize', onResize);
return [1];
}, []);The cleanup function must remove the event listener by returning a function that calls window.removeEventListener('resize', onResize).
Fix the error in the cleanup function that clears an interval.
useEffect(() => {
const id = setInterval(() => {
console.log('Tick');
}, 1000);
return [1];
}, []);The cleanup function must be a function that calls clearInterval(id). Returning clearInterval(id) directly causes an error because cleanup must be a function.
Fill both blanks to add and clean up a window scroll event listener.
useEffect(() => {
function handleScroll() {
console.log('Scrolled');
}
window.[1]('scroll', handleScroll);
return () => {
window.[2]('scroll', handleScroll);
};
}, []);We add the event listener with addEventListener and clean it up with removeEventListener.
Fill all three blanks to create a cleanup function that cancels a subscription and clears a timeout.
useEffect(() => {
const subscription = api.subscribe();
const timeoutId = setTimeout(() => {
console.log('Timeout done');
}, 2000);
return () => {
subscription.[1]();
clearTimeout([2]);
console.log([3]);
};
}, []);The cleanup calls subscription.unsubscribe(), clears the timeout with clearTimeout(timeoutId), and logs a message.