Challenge - 5 Problems
Effect Execution Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
When does this effect run?
Consider this React component using
useEffect. When will the effect's console.log run?React
import React, { useState, useEffect } from 'react'; function Timer() { const [count, setCount] = useState(0); useEffect(() => { console.log('Effect ran'); }, [count]); return <button onClick={() => setCount(count + 1)}>Count: {count}</button>; }
Attempts:
2 left
💡 Hint
Look at the dependency array in useEffect.
✗ Incorrect
The effect runs after every render where the 'count' value changes because 'count' is in the dependency array.
❓ lifecycle
intermediate2:00remaining
Effect cleanup timing
What happens when a component with this effect re-renders due to state change?
React
import React, { useState, useEffect } from 'react'; function Logger() { const [text, setText] = useState(''); useEffect(() => { console.log('Effect setup'); return () => { console.log('Effect cleanup'); }; }, [text]); return <input value={text} onChange={e => setText(e.target.value)} />; }
Attempts:
2 left
💡 Hint
Think about when cleanup functions run in useEffect with dependencies.
✗ Incorrect
The cleanup runs before the next effect runs when the dependency changes, so before the effect runs again on 'text' change.
📝 Syntax
advanced2:00remaining
Identify the effect execution error
Which option causes a syntax error preventing the effect from running?
React
import React, { useEffect } from 'react'; function Demo() { useEffect(() => { console.log('Hello'); }, ); return <div>Demo</div>; }
Attempts:
2 left
💡 Hint
Check the dependency array syntax.
✗ Incorrect
Option A has a trailing comma with no dependency array, causing a syntax error.
❓ state_output
advanced2:00remaining
Effect and state update timing
What will be logged to the console after clicking the button once?
React
import React, { useState, useEffect } from 'react'; function Counter() { const [count, setCount] = useState(0); useEffect(() => { console.log(`Count is ${count}`); }, [count]); return <button onClick={() => setCount(count + 1)}>Increment</button>; }
Attempts:
2 left
💡 Hint
The effect runs after state updates and re-renders.
✗ Incorrect
After clicking, count updates to 1, triggering the effect which logs 'Count is 1'.
🔧 Debug
expert3:00remaining
Why does this effect run infinitely?
This component causes an infinite loop of effect executions. Why?
React
import React, { useState, useEffect } from 'react'; function InfiniteLoop() { const [value, setValue] = useState(0); useEffect(() => { setValue(value + 1); }, [value]); return <div>{value}</div>; }
Attempts:
2 left
💡 Hint
Think about what triggers the effect and what the effect does.
✗ Incorrect
The effect updates 'value' state, which triggers the effect again due to 'value' in dependencies, causing an infinite loop.