React Hooks useEffect Hook 3 — Questions and Answers
Question 1: What does React do when a dependency in useEffect's array changes?
- Runs the cleanup of the previous effect, then re-runs the new effect (Correct answer)
- Skips the effect for that render
- Throws a warning in development
- Resets state to its initial value
Correct answer: Runs the cleanup of the previous effect, then re-runs the new effect
React calls the previous effect's cleanup function before re-running the effect with the new dependency values.
Question 2: In React StrictMode (development), how many times does a useEffect fire on mount?
- Once
- Twice (mount, unmount, remount) to detect side-effect issues (Correct answer)
- Three times
- It varies
Correct answer: Twice (mount, unmount, remount) to detect side-effect issues
StrictMode intentionally double-invokes effects to help detect missing cleanup logic.
Question 3: What does the eslint-plugin-react-hooks exhaustive-deps rule enforce?
- All hooks must be named with 'use'
- All values referenced inside the effect must be listed in the dependency array (Correct answer)
- Effects cannot have cleanup functions
- State updates must be batched
Correct answer: All values referenced inside the effect must be listed in the dependency array
The exhaustive-deps rule warns when you use a value inside useEffect without listing it as a dependency.
Question 4: Which situation would cause an infinite loop with useEffect?
- An empty dependency array with no state updates
- Updating state inside the effect without including it in the dependency array
- Fetching data once on mount
- Updating state inside the effect that is also a dependency of the same effect (Correct answer)
Correct answer: Updating state inside the effect that is also a dependency of the same effect
If you update state that is also listed as a dependency, the effect fires → updates state → fires again endlessly.
Question 5: How should you add an event listener and clean it up with useEffect?
- Add in useEffect with [] and never remove it
- Add in useEffect and return a function that removes the listener (Correct answer)
- Add in useEffect and remove in a separate useEffect
- Event listeners don't need cleanup
Correct answer: Add in useEffect and return a function that removes the listener
Returning a cleanup function that calls removeEventListener ensures no listener leak when the component unmounts.
Question 6: What is the correct term for a function defined inside useEffect that is used as a callback?
- Stable callback
- Effect closure (Correct answer)
- Memoized handler
- Ref callback
Correct answer: Effect closure
Functions inside useEffect form closures over the values present at the time the effect ran.
What does React do when a dependency in useEffect's array changes?