Challenge - 5 Problems
Lifecycle Mastery with Hooks
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ lifecycle
intermediate2:00remaining
What happens when a React component with useEffect([]) mounts?
Consider a React functional component that uses
useEffect with an empty dependency array []. What lifecycle phase does this represent?React
useEffect(() => {
console.log('Effect runs');
}, []);Attempts:
2 left
💡 Hint
Think about when useEffect with empty dependencies triggers.
✗ Incorrect
Using useEffect with an empty dependency array means the effect runs once after the component mounts, similar to componentDidMount in class components.
❓ lifecycle
intermediate2:00remaining
When does a useEffect cleanup function run?
Given this React hook code, when is the cleanup function executed?
useEffect(() => {
console.log('Effect setup');
return () => {
console.log('Cleanup');
};
}, [count]);React
useEffect(() => {
console.log('Effect setup');
return () => {
console.log('Cleanup');
};
}, [count]);Attempts:
2 left
💡 Hint
Cleanup runs before the next effect or unmount.
✗ Incorrect
The cleanup function runs before the effect runs again due to dependency changes and also when the component unmounts.
❓ component_behavior
advanced2:00remaining
What is the output sequence of console logs for this component?
Analyze the following React component and determine the order of console logs when it mounts and then updates due to
count change.React
import React, { useState, useEffect } from 'react'; function Counter() { const [count, setCount] = useState(0); useEffect(() => { console.log('Effect run'); return () => { console.log('Cleanup'); }; }, [count]); return <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>; }
Attempts:
2 left
💡 Hint
Remember cleanup runs before the next effect.
✗ Incorrect
On mount, effect runs. On update (count changes), cleanup runs first, then effect runs again.
📝 Syntax
advanced2:00remaining
Which useEffect hook syntax causes a syntax error?
Identify the option that will cause a syntax error in React when using
useEffect.Attempts:
2 left
💡 Hint
Check the dependency array syntax.
✗ Incorrect
Option D has a trailing comma without a dependency array, causing a syntax error.
🔧 Debug
expert3:00remaining
Why does this useEffect cause an infinite loop?
Examine the code below. Why does the component keep re-rendering infinitely?
const [count, setCount] = useState(0);
useEffect(() => {
setCount(count + 1);
}, [count]);React
const [count, setCount] = useState(0); useEffect(() => { setCount(count + 1); }, [count]);
Attempts:
2 left
💡 Hint
Think about what triggers useEffect and what setCount does.
✗ Incorrect
Updating state inside a useEffect that depends on that state causes the effect to run repeatedly, creating an infinite loop.