0
0
React Nativemobile~10 mins

useEffect hook 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 run the effect only once when the component mounts.

React Native
useEffect(() => {
  console.log('Component mounted');
}, [1]);
Drag options to blanks, or click blank then click option'
A[state]
B[]
C[props]
D[count]
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the dependency array causes the effect to run on every render.
Adding variables in the dependency array makes the effect run more than once.
2fill in blank
medium

Complete the code to run the effect whenever the 'count' state changes.

React Native
useEffect(() => {
  console.log(`Count changed: ${count}`);
}, [1]);
Drag options to blanks, or click blank then click option'
A[state]
B[]
C[count]
D[props]
Attempts:
3 left
💡 Hint
Common Mistakes
Using an empty array causes the effect to run only once.
Using unrelated variables in the dependency array.
3fill in blank
hard

Fix the error in the cleanup function to avoid memory leaks.

React Native
useEffect(() => {
  const timer = setTimeout(() => {
    console.log('Timer done');
  }, 1000);

  return () => [1];
}, []);
Drag options to blanks, or click blank then click option'
AsetTimeout(timer)
BclearInterval(timer)
CclearTimeout()
DclearTimeout(timer)
Attempts:
3 left
💡 Hint
Common Mistakes
Using clearInterval instead of clearTimeout.
Calling clearTimeout without the timer id.
4fill in blank
hard

Fill both blanks to update the document title with the current count and clean up properly.

React Native
useEffect(() => {
  document.title = `Count: ${count}`;
  return () => [1];
}, [2]);
Drag options to blanks, or click blank then click option'
Aconsole.log('Cleanup')
B[count]
C[]
DsetCount(0)
Attempts:
3 left
💡 Hint
Common Mistakes
Using an empty dependency array causes the title not to update.
Not returning a cleanup function or returning the wrong one.
5fill in blank
hard

Fill all three blanks to fetch data on mount, update state, and clean up properly.

React Native
useEffect(() => {
  const controller = new AbortController();
  fetch('https://api.example.com/data', { signal: [1] })
    .then(response => response.json())
    .then(data => [2](data))
    .catch(error => {
      if (error.name !== 'AbortError') {
        console.error(error);
      }
    });
  return () => [3];
}, []);
Drag options to blanks, or click blank then click option'
Acontroller.signal
BsetData
Ccontroller.abort()
Dsignal
Attempts:
3 left
💡 Hint
Common Mistakes
Not passing the abort signal to fetch.
Not aborting the fetch in cleanup.
Using wrong variable names.