0
0
React Nativemobile~10 mins

Memory leak detection in React Native - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to clean up the effect and avoid memory leaks in a React Native component.

React Native
useEffect(() => {
  const subscription = someAPI.subscribe();
  return () => {
    subscription[1]();
  };
}, []);
Drag options to blanks, or click blank then click option'
Aremove
Bsubscribe
Cunsubscribe
Dcancel
Attempts:
3 left
💡 Hint
Common Mistakes
Calling subscribe() again in the cleanup function causes repeated subscriptions.
Not returning a cleanup function leads to memory leaks.
2fill in blank
medium

Complete the code to cancel a timer in React Native to prevent memory leaks.

React Native
useEffect(() => {
  const timer = setTimeout(() => {
    doSomething();
  }, 1000);
  return () => {
    clear[1](timer);
  };
}, []);
Drag options to blanks, or click blank then click option'
Atimeout
Binterval
Ctimer
Ddelay
Attempts:
3 left
💡 Hint
Common Mistakes
Using clearInterval() for a timeout causes the timer to keep running.
Not clearing timers causes memory leaks.
3fill in blank
hard

Fix the error in the cleanup function to prevent memory leaks when using event listeners.

React Native
useEffect(() => {
  const handler = () => console.log('Event');
  window.addEventListener('resize', handler);
  return () => {
    window.removeEventListener('resize', [1]);
  };
}, []);
Drag options to blanks, or click blank then click option'
Ahandler
Bhandler()
C'handler'
D() => handler
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the handler function instead of passing it causes the listener not to be removed.
Passing a string instead of a function reference causes errors.
4fill in blank
hard

Fill both blanks to correctly clean up a subscription and a timer in React Native.

React Native
useEffect(() => {
  const subscription = api.subscribe();
  const timer = setInterval(() => update(), 1000);
  return () => {
    subscription[1]();
    clear[2](timer);
  };
}, []);
Drag options to blanks, or click blank then click option'
Aunsubscribe
Btimeout
Cinterval
Dcancel
Attempts:
3 left
💡 Hint
Common Mistakes
Using clearTimeout() instead of clearInterval() for interval timers.
Not unsubscribing from subscriptions causes memory leaks.
5fill in blank
hard

Fill all three blanks to create a safe effect that fetches data, sets state, and cleans up properly to avoid memory leaks.

React Native
useEffect(() => {
  let isMounted = true;
  fetchData().then(data => {
    if ([1]) {
      setData([2]);
    }
  });
  return () => {
    [3] = false;
  };
}, []);
Drag options to blanks, or click blank then click option'
AisMounted
Bdata
Attempts:
3 left
💡 Hint
Common Mistakes
Not checking if the component is mounted before setting state.
Forgetting to update the flag in the cleanup function.