Hooksbeginner
useEffect Fundamentals
Learn how useEffect synchronizes a component with external systems and how the dependency array controls when it runs.
useEffect lets a function component perform side effects — operations that reach outside the pure render calculation, like fetching data, subscribing to events, or manually manipulating the DOM. It accepts a function to run after the browser has painted the updated DOM, and an optional dependency array that controls when the effect re-runs.
useEffect is like a standing instruction to a personal assistant: 'whenever my calendar (dependencies) changes, redo this specific task, but first undo whatever you did last time' — it's about keeping something in sync with changing inputs, not about a fixed point in a day's schedule.
Key Concepts
1
The dependency array is the crux of useEffect: React compares each value in the array to its value from the previous render, and only re-runs the effect if at least one has changed. An empty array [] means the effect only depends on nothing, so it runs once after the initial mount. Omitting the array entirely makes the effect run after every render.
useEffect[]
2
A cleanup function returned from the effect runs before the effect re-runs (to undo the previous effect) and when the component unmounts. This is essential for anything that would otherwise leak, like intervals, subscriptions, or event listeners.
3
Interviewers frequently test whether candidates understand that useEffect should be thought of as "synchronize with this set of dependencies," not as a lifecycle hook — omitting a dependency to force specific timing is a common source of stale closure bugs, and the ESLint react-hooks/exhaustive-deps rule exists specifically to catch this.
useEffectreact-hooks/exhaustive-deps