React Hooks useEffect Hook 1 — Questions and Answers
Question 1: What is the primary purpose of the useEffect hook?
- To manage component state
- To perform side effects in function components (Correct answer)
- To memoize expensive computations
- To create context values
Correct answer: To perform side effects in function components
useEffect lets you synchronize a component with external systems by running side effects after render.
Question 2: When does a useEffect with an empty dependency array [] run?
- On every render
- Only once after the initial render (Correct answer)
- Only when dependencies change
- Never
Correct answer: Only once after the initial render
An empty dependency array tells React to run the effect only once, after the first render.
Question 3: What does the cleanup function returned from useEffect do?
- Prevents the component from re-rendering
- Runs before the next effect or on unmount to cancel subscriptions (Correct answer)
- Clears the state
- Triggers a new render
Correct answer: Runs before the next effect or on unmount to cancel subscriptions
The cleanup function runs before the effect re-fires and on component unmount to avoid memory leaks.
Question 4: What happens when you omit the dependency array from useEffect?
- The effect runs only once
- The effect never runs
- The effect runs after every render (Correct answer)
- React throws an error
Correct answer: The effect runs after every render
Without a dependency array, useEffect runs after every completed render.
Question 5: Which of the following is a valid useEffect cleanup?
- useEffect(() => { return clearInterval(id); })
- useEffect(() => { return () => clearInterval(id); }) (Correct answer)
- useEffect(() => clearInterval(id))
- useEffect.cleanup(() => clearInterval(id))
Correct answer: useEffect(() => { return () => clearInterval(id); })
The cleanup must be a function returned from the effect callback, not the direct result of clearInterval.
Question 6: In which phase does useEffect run relative to the browser paint?
- Before the DOM is updated
- Before the browser paints
- After the browser has painted (Correct answer)
- Synchronously during render
Correct answer: After the browser has painted
useEffect is deferred and runs asynchronously after the browser has painted the screen.
What is the primary purpose of the useEffect hook?