React: Search after the typing stops

Searching on every key press is wasteful. Wait until the user pauses, using an effect whose cleanup cancels the previous wait.

What to build

A search box that filters a list 300 ms after the last key press.

Requirements

  • A controlled input with the id search. The list ul#results shows the cities that contain the query (ignoring case); all of them for an empty query.
  • The query used for filtering is updated only 300 ms after the last change to the input; while a change is waiting, a p with the id status says Searching…, and otherwise it says N results.
  • If no city matches, the list is empty and the status says 0 results.

Constraints

Use setTimeout in an effect with a cleanup; do not filter on every key press.

Example

Typing "on" quickly shows "Searching…" and the old list, then after a moment London and Boston only.

Why it works

Each change starts a new timeout and the cleanup cancels the one before, so only the last pause updates the query, and the list is computed from the query during render.

Hints

Hint 1

Keep two values: what is typed (updated on every key) and the query (updated by an effect after 300 ms).

Hint 2

The effect starts a setTimeout and its cleanup clears it, so each new key press cancels the previous wait.

Solution

Show one correct solution (try it yourself first)
import { useEffect, useState } from "react";

const CITIES = ["Dhaka", "London", "Paris", "Boston", "Delhi", "Tokyo"];

export default function App() {
  const [text, setText] = useState("");
  const [query, setQuery] = useState("");

  useEffect(() => {
    const id = setTimeout(() => setQuery(text), 300);
    return () => clearTimeout(id);
  }, [text]);

  const shown = CITIES.filter((c) => c.toLowerCase().includes(query.toLowerCase()));
  const waiting = text !== query;

  return (
    <div>
      <input id="search" value={text} onChange={(e) => setText(e.target.value)} />
      <p id="status">{waiting ? "Searching…" : shown.length + " results"}</p>
      <ul id="results">
        {shown.map((c) => (
          <li key={c}>{c}</li>
        ))}
      </ul>
    </div>
  );
}

Lesson: Effects: syncing with the outside world →