React · Lesson 6 of 15 · 4 min
Deep Dive into useEffect Hook
Interviewers use useEffect to test your understanding of component lifecycle, side effects, and performance. Get this wrong, and you signal you can't write robust components.
After this, you will be able to explain the useEffect dependency array, cleanup functions, and common pitfalls like race conditions and stale closures with the precision interviewers expect. This isn't about syntax; it's about proving you can build stable, leak-free components.
The Dependency Array Controls the "When"
The second argument to useEffect is the dependency array. It tells React when to re-run your effect. There are three possibilities, and you need to know exactly what each one does.
[dep1, dep2](Array with values): This is the most common case. The effect runs after the initial render, and then again only if any value in the array has changed since the last render. React usesObject.isfor comparison.[](Empty array): The effect runs exactly once, after the initial render. The cleanup function runs when the component unmounts. This is the correct choice for "on mount" setup like event listeners or initial data fetches.- (Omitted): If you don't provide the array, the effect runs after every single render. This is rarely what you want and is a common source of performance problems and bugs.
The trap: Candidates often confuse an empty array with an omitted array. Be precise. [] means "run once on mount". Omitting it means "run on every render". If an interviewer asks when you'd omit it, the answer is almost never.
The Cleanup Function Prevents Leaks
If your effect subscribes to something, it must unsubscribe. If it starts a timer, it must clear it. If it opens a connection, it must close it. Forgetting to do this creates memory leaks that will crash your application.
The function you return from your effect is the cleanup function. React runs it before re-running the effect, and one last time when the component unmounts.
import React, { useState, useEffect } from 'react';
function TimerComponent() {
const [ticks, setTicks] = useState(0);
useEffect(() => {
console.log('Setting up interval...');
const intervalId = setInterval(() => {
// The functional update form avoids needing `ticks` in the dependency array.
setTicks(t => t + 1);
}, 1000);
// This is the cleanup function.
// React runs it when the component unmounts.
return () => {
console.log('Clearing interval...');
clearInterval(intervalId);
};
}, []); // Empty array ensures this runs only once on mount and unmount.
return <div>Timer Ticks: {ticks}</div>;
}
Without the return () => { clearInterval(intervalId); };, the timer would keep running in the background forever, even after the component is gone. This is a classic interview question.
Fetching Data Without Race Conditions
Fetching data is the canonical useEffect example. The naive implementation is simple, but it has a critical flaw: a race condition.
Imagine a user can switch between profiles. They click "Profile A", then quickly click "Profile B". If the request for A is slow and the request for B is fast, B's data will arrive first, then A's data will arrive and overwrite it. The UI will incorrectly show Profile A.
The solution is to ignore responses from stale requests. The modern way is with an AbortController, which you clean up in the effect's return function.
An interviewer might ask: "A user is rapidly changing a filter that triggers an API call. What problems can occur and how would you solve them?"
Your answer should identify the race condition and describe a cancellation mechanism. Mentioning
AbortControllerin theuseEffectcleanup function is a strong signal.
Dependencies, Stale Closures, and Referential Equality
The eslint-plugin-react-hooks/exhaustive-deps rule is not just a suggestion. It prevents a class of bugs caused by "stale closures".
If your effect uses a piece of state or a prop but doesn't list it in the dependency array, the function "closes over" the value of that variable from the first time the effect ran. It will never see the updated value.
The trap: An effect that uses count but has an empty dependency array ([]) will always see count as its initial value. This is a common "what's wrong with this code?" problem.
The other side of this is referential equality. If you define an object or function inside your component body, it gets a new identity on every render. If you list it as a dependency, your effect will re-run on every render, even if the "value" is the same.
This is why you use useMemo for objects/arrays and useCallback for functions that are passed into useEffect's dependency array. They stabilize the reference, preventing unnecessary effect runs. You don't need to master them for this lesson, but you need to know why they are relevant to useEffect.
Try it
Implement a debounced search input. When the user types, wait 300ms before logging an "API call" to the console. If they type again within that window, the previous timer must be cancelled and a new one started. This will test your handling of state, timers, and cleanup in a single, practical exercise.
Next: We'll look at how to manage more complex component logic and interact with the DOM directly using useRef and useReducer for Complex State.
Lock it in — apply this lesson under interview conditions.