Skip to main content
Intermediate Step-by-Step Tutorial 10 min read React 19 + TypeScript 5

React Hooks Guide: useState, useEffect & Stale Closures

Build bug-free React 19 UI components with functional state updates, clean AbortController effect cleanup, and TypeScript safety.

Written by MockAttempt Engineering Editorial Desk (Curriculum & Code Verification Review Panel) Reviewed by Ravi Shankar Mishra
Last updated: Verification Policy

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.

React 19 + TypeScript 5
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..." />;
}
Expected Output
Fast typing aborts superseded HTTP requests so `items` strictly matches the final `query`.
Step-by-Step Execution
  1. Whenever `query` changes, React executes the previous effect’s cleanup (`controller.abort()`).
  2. 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.

Optional Next Step

Have Questions About Learning React.js Structured Cohorts?

Request the FDCP syllabus & weekend batch schedule from an Academic Counselor.

View FDCP Details →
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.