0
0
Reactframework~5 mins

Cleanup function in React - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ABefore the component unmounts or before the effect runs again
BOnly when the component mounts
COnly after the component updates
DNever, cleanup functions are optional
What is a common use case for a cleanup function in useEffect?
AStarting a timer
BCleaning up a timer or subscription
CRendering UI elements
DFetching data
What happens if you don't clean up a subscription in useEffect?
AThe subscription stops automatically
BReact throws an error
CThe subscription continues and may cause memory leaks
DThe component re-renders infinitely
How do you define a cleanup function inside useEffect?
ABy returning a function from useEffect
BBy calling a function inside useEffect
CBy passing a function as a dependency
DBy using a separate useCleanup hook
Which React hook commonly uses cleanup functions?
AuseMemo
BuseState
CuseContext
DuseEffect
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.