useEffect in React: Dependencies, Cleanup, and Async Examples
Build a reliable mental model for React Effects, then trace a profile loader that cancels stale work. Includes dependency fixes, cleanup patterns, and exercises.
KnowledgeGate Team
Exam prep & CS education

Correct JSX does not keep a timer, browser title, connection, or request aligned with the latest props and state. useEffect synchronises those external systems; it is not a default home for code after a render.
What useEffect is for, and what should stay in render
Rendering calculates UI from current props and state; an Effect synchronises an external system afterward. Use one for document.title, window subscriptions, timers, or data requests for userId. Calculate const total = price * quantity and filter in-memory arrays during render because neither touches an external system.
Events have their own owner. handleBuy() should send the purchase request when the learner clicks Buy; do not set shouldBuy = true and wait for an Effect. The click caused the work. Keep this distinction in view across Coding & Skill Development Courses and Web Development.
Read an Effect as setup, dependencies, and cleanup
Read an Effect as useEffect(setup, dependencies). In useEffect(() => { document.title = `Cart (${count})`; }, [count]), count = 2 makes the title Cart (2); changing the count to 4 produces Cart (4). This assignment owns no resource, so it needs no cleanup.
A browser subscription does own a resource:
useEffect(() => {
function handleResize() {
console.log(`${panelId}:${window.innerWidth}`);
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, [panelId]);With [panelId], changing "overview" to "details" first removes the overview handler and then installs the details handler. Unmounting removes the details handler. The same function reference must be passed to both listener calls; otherwise the old subscription remains attached.
Instead of asking how to run once, ask which external state must match the dependencies and how to undo the old setup.
Worked example: a profile loader that cannot be overwritten by stale work

A timer-based request makes the cleanup race visible:
import { useEffect, useState } from "react";
const PROFILES = {
1: { name: "Asha", tasks: 5 },
2: { name: "Kabir", tasks: 3 }
};
function ProfileCard({ userId }) {
const [profile, setProfile] = useState(null);
const [status, setStatus] = useState("");
useEffect(() => {
setProfile(null);
setStatus(`Loading user ${userId}...`);
const delay = userId === 1 ? 800 : 200;
const timerId = setTimeout(() => {
const nextProfile = PROFILES[userId];
setProfile(nextProfile);
setStatus(`Loaded ${nextProfile.name}`);
}, delay);
return () => clearTimeout(timerId);
}, [userId]);
return (
<section>
<p>{status}</p>
{profile && <h2>{profile.name} has {profile.tasks} tasks.</h2>}
</section>
);
}
export default function App() {
const [userId, setUserId] = useState(1);
return (
<main>
<button onClick={() => setUserId(1)}>Load Asha</button>
<button onClick={() => setUserId(2)}>Load Kabir</button>
<ProfileCard userId={userId} />
</main>
);
}On the settled default path, the screen first shows Loading user 1.... After 800 ms, it shows Loaded Asha and Asha has 5 tasks.
The first Effect clears any previous profile, sets the loading message, computes Asha's 800 ms delay, and schedules a timer. Its callback stores Asha's profile and loaded status, so the next render shows both final lines.
Now trace a rapid switch. At t = 0, Asha's 800 ms timer starts. At t = 100 ms, clicking Load Kabir changes userId. Before the new setup runs, cleanup clears Asha's timer. Kabir's 200 ms timer then starts at t = 100 ms, so it completes at about t = 300 ms because 100 + 200 = 300. The final UI is Loaded Kabir and Kabir has 3 tasks. Asha never gets a chance to overwrite it.
The Effect reads userId, so [userId] declares when to replace its external work. React's setters and module-level PROFILES do not change per render. Each setup closes over a timerId, and cleanup clears that exact timer.
Cleanup prevents stale async results, not just memory leaks
Remove return () => clearTimeout(timerId). Kabir completes at about t = 300 ms, but Asha's older timer completes at about t = 800 ms and overwrites the screen with Loaded Asha and Asha has 5 tasks. Both callbacks succeeded; their completion order caused an ordering race. Cleanup prevents an old dependency snapshot from publishing into the current UI.
Real requests can use the same pattern:
useEffect(() => {
const controller = new AbortController();
async function loadProfile() {
try {
const response = await fetch(`/api/users/${userId}`, {
signal: controller.signal
});
if (!response.ok) throw new Error("Could not load profile");
const nextProfile = await response.json();
setProfile(nextProfile);
} catch (error) {
if (error.name !== "AbortError") setStatus(error.message);
}
}
loadProfile();
return () => controller.abort();
}, [userId]);The Effect callback must return synchronous cleanup, not a Promise, so the async function is nested. AbortError is the expected cleanup path; other failures remain visible.

Dependency arrays: every render, an empty array, or selected values
Dependencies describe what setup reads and when its synchronisation may need replacement.
Form | Meaning |
|---|---|
No second argument | Consider the Effect after every render. |
| Setup reads no reactive value from the component. It must still tolerate cleanup and a future remount. |
| Replace the synchronisation when |
[] does not mean "once forever": a component can unmount and remount. If an Effect reads query but declares [], changing query from "react" to "hooks" starts no work for "hooks". Declare [query]; do not silence the warning.
Identity matters too. const options = { roomId } in the component creates a fresh object every render, so [options] repeatedly restarts the connection. Build { roomId } inside the Effect and depend on [roomId]. Define an Effect-only inline helper inside the Effect when practical.
Common useEffect errors and the smallest correct fix
Deriving state with an Effect. Building
fullNamefromfirstName = "Asha"andlastName = "Rao"in state adds a render. Calculateconst fullName = firstName + " " + lastNameduring render to get Asha Rao immediately.Updating its own dependency.
setCount(count + 1)in an Effect with[count]triggers a loop. Move the update to its event or redesign the state flow.Making the callback async.
useEffect(async () => { ... }, [userId])returns a Promise, not cleanup. Nest and call the async function, then return synchronous cleanup.Omitting a dependency to stop requests. Leaving out
userIdcaptures stale input. Keep[userId]and cancel work that becomes obsolete.
Some development setups rehearse setup, cleanup, and setup again to expose omissions. The second setup must behave like a clean start. Do not hide it with a ref: clear timers, remove listeners with the function used to add them, and disconnect connections.
Exercises and output checks
In
ClockTitle({ seconds }), 12 must setStudy timer: 12s, and 11 must update it toStudy timer: 11s. Use[seconds]and no Effect state.Build
OnlineStatuswithwindow.addEventListener("online", handleOnline)and matching removal. Mount, unmount, and remount must leave exactly one active listener.Give Asha 5 tasks and a 700 ms delay; give Kabir 3 tasks and a 150 ms delay. Start Asha, then click Kabir after 50 ms. Kabir finishes at about 200 ms because 50 + 150 = 200. The final UI must remain
Loaded KabirandKabir has 3 tasksafter 700 ms.
Predict three results: unread values do not alter the dependency list; an unmounted timer cannot update UI; without cleanup, Exercise 3 ends with stale Asha. Review semantic buttons and headings with HTML Interview Questions for Freshers: Tags, Forms, Attributes.
The short version and the next study step
Use Effects only for external synchronisation. List every reactive value read, pair setup with cleanup, and cancel obsolete work. Calculate derived values during render; keep click-caused work in handlers. Switching at t = 100 ms must finish on Kabir, never stale Asha. For a complete frontend and backend path, continue with the MERN Stack Course.
Keep learning
useEffect Explained: Dependency Arrays, Cleanup Functions and the Bugs Interviewers Probe
Compare all three dependency-array forms, follow teardown before setup, and repair the interval that captures count as zero and freezes the UI at one.
Redux Toolkit Integration in React: Store, Slices, Async Thunks, and Runnable Examples
Build a Study Planner that traces each click through Redux Toolkit, calculates progress, filters tasks, loads deterministic async data and exposes failures.
React Hooks Explained: useState, useEffect, useMemo, and Custom Hooks with Interview Questions
Build the right mental model for React Hooks, then trace a debounced search component from keystroke to filtered result.
NPM and package.json in Node.js: Setup, Scripts, Dependencies, and SemVer
Build a small Node.js project from an empty folder, install Lodash, add reusable npm scripts, compare the manifest and lockfile, and practise SemVer ranges.





