Explain React useEffect lifecycle, dependency arrays, and race-condition cleanup
Quick Summary: useEffect synchronizes React UI state with external systems (APIs, subscriptions, timers) after paint, re-running whenever dependencies change and invoking the returned cleanup function beforehand to cancel stale requests or listeners.
Direct Interview Answer
Do not think of useEffect merely as lifecycle methods—it declares synchronization. If you omit dependencies, effects read stale closures; if you mutate state synchronously inside render logic, you bypass safe scheduling.
Returning a cleanup function ensures timers, WebSocket listeners, or an in-flight AbortController abort cleanly before the next effect runs or when the component unmounts.
Detailed Technical Explanation
In React Strict Mode during development, React intentionally mounts → unmounts → remounts components once to expose missing cleanup functions! Properly aborting fetches via AbortController stops older slow search API responses from overwriting newer typed query results.
Practical Walkthrough
Search effect cancelling superseded API requests cleanly.
import { useEffect, useState } from "react";
export function CourseSearch({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
if (!query.trim()) return;
const controller = new AbortController();
fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
.then((r) => r.json())
.then((data) => setResults(data.items || []))
.catch((err) => { if (err.name !== "AbortError") console.error(err); });
return () => controller.abort();
}, [query]);
return <ul>{results.map((item) => <li key={item.id}>{item.title}</li>)}</ul>;
}
Out-of-order stale HTTP fetches abort automatically when user types quickly.
Real-World Production Use Case
Live autocomplete dropdowns, real-time chat WebSocket subscriptions, and synchronized browser event listeners.
Common Interview Mistakes to Avoid
- Leaving out AbortController cleanup on fetch effects, causing stale slow responses to overwrite current UI state.
- Using useEffect merely to derive values (e.g., fullName = first + last) instead of computing during render.