Recall & Review
beginner
What is a cleanup function in React's useEffect hook?
A cleanup function is a function returned from useEffect that React runs before the component unmounts or before the effect runs again. It helps to clean up resources like timers or subscriptions to avoid memory leaks.
Click to reveal answer
beginner
When is the cleanup function inside useEffect called?
The cleanup function runs right before the component unmounts and also before the effect runs again if the dependencies change.
Click to reveal answer
beginner
Why should you use a cleanup function in React effects?
To stop ongoing processes like timers, cancel subscriptions, or remove event listeners. This prevents bugs and memory leaks when components update or disappear.
Click to reveal answer
intermediate
Show a simple example of a cleanup function in useEffect that clears a timer.
useEffect(() => {
const timer = setTimeout(() => {
console.log('Timer done');
}, 1000);
return () => clearTimeout(timer);
}, []);Click to reveal answer
intermediate
What happens if you forget to add a cleanup function for subscriptions in useEffect?
The subscription keeps running even after the component unmounts, causing memory leaks and possibly unexpected behavior or errors.
Click to reveal answer
When does React call the cleanup function returned by useEffect?
✗ Incorrect
React calls the cleanup function before unmounting and before running the effect again if dependencies change.
What is a common use case for a cleanup function in useEffect?
✗ Incorrect
Cleanup functions are used to stop timers or unsubscribe from events to avoid memory leaks.
What happens if you don't clean up a subscription in useEffect?
✗ Incorrect
Without cleanup, subscriptions keep running after unmount, causing memory leaks.
How do you define a cleanup function inside useEffect?
✗ Incorrect
You return a function from useEffect to define the cleanup function.
Which React hook commonly uses cleanup functions?
✗ Incorrect
useEffect is the hook where cleanup functions are defined to manage side effects.
Explain what a cleanup function is in React and why it is important.
Think about what happens when a component disappears or updates.
You got /3 concepts.
Describe how you would use a cleanup function to clear a timer in a React component.
Remember to stop the timer when the component unmounts.
You got /3 concepts.