Complete the code to clean up the effect and avoid memory leaks in a React Native component.
useEffect(() => {
const subscription = someAPI.subscribe();
return () => {
subscription[1]();
};
}, []);To avoid memory leaks, you must unsubscribe from subscriptions when the component unmounts. The correct method is unsubscribe().
Complete the code to cancel a timer in React Native to prevent memory leaks.
useEffect(() => {
const timer = setTimeout(() => {
doSomething();
}, 1000);
return () => {
clear[1](timer);
};
}, []);To clear a timeout timer, use clearTimeout() in the cleanup function.
Fix the error in the cleanup function to prevent memory leaks when using event listeners.
useEffect(() => {
const handler = () => console.log('Event');
window.addEventListener('resize', handler);
return () => {
window.removeEventListener('resize', [1]);
};
}, []);The cleanup must pass the exact same function reference used in addEventListener. Passing handler without parentheses is correct.
Fill both blanks to correctly clean up a subscription and a timer in React Native.
useEffect(() => {
const subscription = api.subscribe();
const timer = setInterval(() => update(), 1000);
return () => {
subscription[1]();
clear[2](timer);
};
}, []);Use unsubscribe() to stop the subscription and clearInterval() to clear the interval timer.
Fill all three blanks to create a safe effect that fetches data, sets state, and cleans up properly to avoid memory leaks.
useEffect(() => {
let isMounted = true;
fetchData().then(data => {
if ([1]) {
setData([2]);
}
});
return () => {
[3] = false;
};
}, []);Use a flag isMounted to check if the component is still mounted before setting state. Set isMounted = false in cleanup to avoid memory leaks.