Challenge - 5 Problems
Unmounting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What happens when a React component unmounts?
Consider a React functional component that uses
useEffect with a cleanup function. What is the behavior of the cleanup function during the unmounting phase?React
import React, { useEffect } from 'react'; function Timer() { useEffect(() => { const id = setInterval(() => console.log('tick'), 1000); return () => clearInterval(id); }, []); return <div>Timer running</div>; }
Attempts:
2 left
💡 Hint
Think about what happens to side effects when a component is removed from the screen.
✗ Incorrect
In React, the cleanup function returned by useEffect runs when the component unmounts to clean up side effects like timers or subscriptions.
❓ lifecycle
intermediate1:30remaining
Which React hook is best for cleanup on unmount?
You want to perform cleanup logic when a functional component unmounts. Which hook and pattern should you use?
Attempts:
2 left
💡 Hint
Cleanup logic is usually inside a return function of a hook that runs effects.
✗ Incorrect
useEffect with an empty dependency array runs once on mount and its return function runs on unmount, perfect for cleanup.
🔧 Debug
advanced2:30remaining
Why does this cleanup not run on unmount?
Identify why the cleanup function does not run when the component unmounts in this code:
React
import React, { useEffect } from 'react'; function Example() { useEffect(() => { const id = setTimeout(() => console.log('done'), 1000); }, []); return <div>Example</div>; }
Attempts:
2 left
💡 Hint
Check if useEffect returns a function for cleanup.
✗ Incorrect
Without returning a cleanup function from useEffect, React has nothing to run on unmount.
❓ state_output
advanced2:00remaining
What is the console output when a component unmounts?
Given this React component, what will be logged to the console when the component unmounts?
React
import React, { useEffect } from 'react'; function Logger() { useEffect(() => { console.log('Mounted'); return () => console.log('Unmounted'); }, []); return <div>Logger</div>; }
Attempts:
2 left
💡 Hint
Remember the order of useEffect and its cleanup function.
✗ Incorrect
The effect runs on mount logging "Mounted"; the cleanup runs on unmount logging "Unmounted".
🧠 Conceptual
expert3:00remaining
Why is cleanup important in React unmounting phase?
Why should you always include cleanup logic in useEffect when your component sets up subscriptions or timers?
Attempts:
2 left
💡 Hint
Think about what happens if timers or subscriptions keep running after the component is gone.
✗ Incorrect
Without cleanup, timers or subscriptions continue running causing memory leaks and bugs.