Bird
Raised Fist0
Reactframework~10 mins

Common lifecycle use cases in React - Interactive Code Practice

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

Complete the code to create a state variable using React hooks.

React
const [count, [1]] = useState(0);
Drag options to blanks, or click blank then click option'
AchangeCount
BgetCount
CupdateCount
DsetCount
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function name that does not start with 'set'.
Confusing the updater function with the state variable.
2fill in blank
medium

Complete the code to run a side effect only once when the component mounts.

React
useEffect(() => {
  console.log('Component mounted');
}, [1]);
Drag options to blanks, or click blank then click option'
A[null]
B[]
C[true]
D[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Leaving the dependency array empty (undefined) causes the effect to run after every render.
Passing non-empty arrays causes the effect to run multiple times.
3fill in blank
hard

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

React
useEffect(() => {
  const timer = setTimeout(() => {
    console.log('Timeout');
  }, 1000);
  return () => [1];
}, []);
Drag options to blanks, or click blank then click option'
AclearTimeout(timer)
BclearInterval(timer)
CcancelTimeout(timer)
DstopTimeout(timer)
Attempts:
3 left
💡 Hint
Common Mistakes
Using clearInterval instead of clearTimeout.
Not returning a cleanup function at all.
4fill in blank
hard

Fill both blanks to update state and log the new value after the button click.

React
const handleClick = () => {
  setCount([1]);
  console.log('Count is now:', [2]);
};
Drag options to blanks, or click blank then click option'
Acount + 1
Bcount
Ccount - 1
DsetCount
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to log the updated count immediately after setCount (which is async).
Using setCount inside console.log.
5fill in blank
hard

Fill all three blanks to fetch data on mount and store it in state.

React
useEffect(() => {
  async function fetchData() {
    const response = await fetch([1]);
    const data = await response.[2]();
    [3](data);
  }
  fetchData();
}, []);
Drag options to blanks, or click blank then click option'
A'https://api.example.com/data'
Bjson
CsetData
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text' instead of 'json' to parse the response.
Not calling the state updater function.

Practice

(1/5)
1. What is the primary purpose of the useEffect hook in React functional components?
easy
A. To define event handlers
B. To declare state variables
C. To run code after the component renders or updates
D. To style components dynamically

Solution

  1. Step 1: Understand the role of useEffect

    The useEffect hook runs side effects like data fetching or timers after rendering.
  2. Step 2: Compare with other options

    Declaring state is done with useState, event handlers are functions, and styling is separate.
  3. Final Answer:

    To run code after the component renders or updates -> Option C
  4. Quick Check:

    useEffect runs side effects after render [OK]
Hint: useEffect runs code after render or update [OK]
Common Mistakes:
  • Confusing useEffect with useState
  • Thinking useEffect is for styling
  • Believing useEffect defines event handlers
2. Which of the following is the correct syntax to run an effect only once when a React component mounts?
easy
A. useEffect(() => { console.log('Mounted'); });
B. useEffect(() => { console.log('Mounted'); }, []);
C. useEffect(() => { console.log('Mounted'); }, [() => {}]);
D. useEffect(() => { console.log('Mounted'); }, [{}]);

Solution

  1. Step 1: Understand dependency array in useEffect

    An empty array [] means the effect runs once on mount only.
  2. Step 2: Analyze other options

    Omitting dependencies runs effect after every render; arrays with unstable values like functions or objects run on every render since they are recreated.
  3. Final Answer:

    useEffect(() => { console.log('Mounted'); }, []); -> Option B
  4. Quick Check:

    Empty array runs effect once on mount [OK]
Hint: Empty dependency array means run once on mount [OK]
Common Mistakes:
  • Omitting dependency array causes repeated runs
  • Using non-empty arrays runs effect multiple times
  • Putting recreated functions or objects in dependency array causes re-runs
3. Consider this React component:
function Timer() {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return <div>Count: {count}</div>;
}

What will be displayed after 3 seconds?
medium
A. Count: 0
B. Count: 1
C. Count: 1000
D. Count: 3

Solution

  1. Step 1: Understand the interval effect

    The effect sets an interval that increments count every 1000ms (1 second).
  2. Step 2: Calculate count after 3 seconds

    After 3 intervals, count increments from 0 to 3.
  3. Final Answer:

    Count: 3 -> Option D
  4. Quick Check:

    Interval increments count every second [OK]
Hint: Interval increments count every second [OK]
Common Mistakes:
  • Ignoring cleanup function
  • Thinking count stays 0
  • Confusing milliseconds with count value
4. What is wrong with this React useEffect usage?
useEffect(() => {
  const timer = setTimeout(() => {
    console.log('Hello');
  }, 1000);
});
medium
A. Missing dependency array causes multiple timeouts to be set on every render
B. setTimeout is not allowed inside useEffect
C. console.log cannot be used inside useEffect
D. The timeout duration must be less than 500ms

Solution

  1. Step 1: Check dependency array presence

    Without a dependency array, the effect runs after every render, creating a new timeout each time.
  2. Step 2: Understand consequences

    This causes multiple timers to accumulate (no cleanup returned), leading to multiple console.logs firing.
  3. Final Answer:

    Missing dependency array causes multiple timeouts to be set on every render -> Option A
  4. Quick Check:

    Missing dependencies cause repeated effect runs [OK]
Hint: Always add dependency array to avoid repeated effects [OK]
Common Mistakes:
  • Thinking setTimeout is disallowed in useEffect
  • Believing console.log can't be used
  • Assuming timeout duration limits
5. You want to fetch user data only when the userId prop changes in a React component. Which useEffect hook is correct?
function UserProfile({ userId }) {
  const [user, setUser] = React.useState(null);

  useEffect(() => {
    fetch(`https://api.example.com/users/${userId}`)
      .then(res => res.json())
      .then(data => setUser(data));
  }, ???);

  return <div>{user ? user.name : 'Loading...'}</div>;
}
hard
A. [userId]
B. [user]
C. []
D. [fetch]

Solution

  1. Step 1: Identify when to run the effect

    The effect should run only when userId changes to fetch new data.
  2. Step 2: Choose correct dependency array

    Including userId in the dependency array triggers effect on its change.
  3. Final Answer:

    [userId] -> Option A
  4. Quick Check:

    Dependency array controls when effect runs [OK]
Hint: Put changing props in dependency array [OK]
Common Mistakes:
  • Using empty array runs effect only once
  • Using state variable instead of prop
  • Including functions like fetch in dependencies
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard