useEffect Questions and Answers
1. Discuss the difference between using an empty dependency array ([]) and omitting the
dependency array altogether in useEffect.
Using an empty dependency array ([]) in useEffect means the effect runs only once after the initial
render. This is equivalent to componentDidMount in class components.
Omitting the dependency array altogether means the effect runs after every render, which can lead
to performance issues if not handled correctly, especially if the effect involves expensive operations.
2. Explain how to handle cleanup in useEffect and why it is necessary.
Cleanup in useEffect is handled by returning a function inside the useEffect. This function is
executed when the component unmounts or before the effect re-runs.
It is necessary to prevent memory leaks and unintended side effects, such as multiple event
listeners or timers running in parallel.
3. Discuss the common pitfalls or mistakes to avoid when using useEffect.
Common pitfalls include:
- Not specifying a dependency array or having an incorrect one, causing unexpected re-renders.
- Causing infinite loops by updating state within the effect without proper dependencies.
- Forgetting cleanup for effects like subscriptions, timers, or event listeners.
- Using stale or outdated variables due to closures.
4. Explain how to conditionally run effects in useEffect based on certain conditions.
To conditionally run effects, include the relevant variables in the dependency array. Inside the effect,
use conditional logic to run specific code only when needed.
Example:
useEffect(() => {
if (isLoggedIn) {
fetchUserData();
}, [isLoggedIn]);