Learning Objectives
- Use updater callbacks `setCount(prev => prev + 1)` whenever next state depends on current state.
- Eliminate redundant `useEffect` chains by computing derived state inline during render.
- Prevent stale async race conditions inside search/filter effects via `AbortController` cleanup.
Prerequisites
- JavaScript ES6+, destructuring, and async Promises
You Might Not Need That useEffect
The cleanest React components compute derived values — such as filtered lists or formatted totals — directly during render instead of duplicating state inside a useEffect. Reserve useEffect strictly for synchronizing with systems outside React: network subscriptions, browser timers, DOM focus, or WebSockets.
Practise React & JS interview questions via Frontend Mock Tests or master React 19 + Angular 19 in our Frontend Developer Career Program.
Practical Programming Examples
TypeScript Search Input with AbortController Cleanup in React 19
Prevent out-of-order stale API responses from overwriting newer keystrokes using useEffect cleanup.
import { useEffect, useState } from 'react';
export function TopicSearchBox() {
const [query, setQuery] = useState('');
const [items, setItems] = useState<string[]>([]);
useEffect(() => {
const trimmed = query.trim();
if (!trimmed) {
setItems([]);
return;
}
const controller = new AbortController();
fetch(`/api/topics?q=${encodeURIComponent(trimmed)}`, { signal: controller.signal })
.then((res) => res.json())
.then((data: string[]) => setItems(data))
.catch((err) => {
if (err.name !== 'AbortError') setItems([]);
});
return () => controller.abort();
}, [query]);
return <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Filter topics..." />;
}
Fast typing aborts superseded HTTP requests so `items` strictly matches the final `query`.
- Whenever `query` changes, React executes the previous effect’s cleanup (`controller.abort()`).
- Aborted `fetch` promises reject with `AbortError`, safely ignored instead of overwriting fresh state.
Common Mistakes to Avoid
- Writing `setCount(count + 1)` three times sequentially (uses stale snapshot `count` instead of `c => c + 1`).
- Omitting `useEffect` dependencies or silencing ESLint `exhaustive-deps` warnings.
Production Best Practices
- Compute derived values directly during render instead of syncing state variables in effects.
- Keep state normalized and close to where it is consumed.
Technical Interview Relevance
Core React machine-coding evaluation criteria (race-condition handling, re-render minimization, functional state updates).
Practice & Self-Check Questions
Why does React StrictMode mount-unmount-remount effects twice in development?
To verify immediately that every `useEffect` implements symmetric cleanup and breaks cleanly if cleanup is missing.