Skip to main content

Search as you type

A product search box. Every keystroke changes the query, but with debounce on the request is sent only when you stop typing. Counters show how many changes you typed and how many requests reached the network.

beginneruseFetchdebounce
import { useFetch } from "@hyper-fetch/react";
import { useEffect, useState } from "react";

import { client, searchProducts } from "./api";

export const App = () => {
const [query, setQuery] = useState("");
const [debounce, setDebounce] = useState(true);
const [keystrokes, setKeystrokes] = useState(0);
const [sent, setSent] = useState<string[]>([]);

// With `bounce`, a changed query waits until typing pauses for `bounceTime` ms. Only that last value is sent.
const { data, error, loading, bounce } = useFetch(
// `select` is a dummyjson query param: the API returns only these fields.
searchProducts.setQueryParams({ q: query, limit: 8, select: "title,price,thumbnail" }),
{ bounce: debounce, bounceType: "debounce", bounceTime: 400 },
);

let status = "idle";
if (bounce.active) status = "waiting for typing to stop";
else if (loading) status = "loading";

// Count what really reaches the network.
useEffect(
() =>
client.requestManager.events.onRequestStart(({ request }) => {
setSent((entries) => [`q="${request.queryParams.q}"`, ...entries]);
}),
[],
);

return (
<main className="container">
<hgroup>
<h1>Product search</h1>
<p>Type fast. With debounce on, one request is sent when you stop typing instead of one per key.</p>
</hgroup>

<input
type="search"
placeholder="Search products, for example phone"
aria-label="Search products"
value={query}
onChange={(event) => {
setQuery(event.target.value);
setKeystrokes((count) => count + 1);
}}
/>
<label>
<input
type="checkbox"
role="switch"
checked={debounce}
onChange={(event) => setDebounce(event.target.checked)}
/>
Debounce (bounceTime 400 ms)
</label>

<div className="stats">
<article>
<strong>{keystrokes}</strong>
<small className="muted">changes typed</small>
</article>
<article>
<strong>{sent.length}</strong>
<small className="muted">requests sent</small>
</article>
<article>
<strong>{status}</strong>
<small className="muted">status</small>
</article>
</div>

<div className="grid-2">
<section>
{error && <p>Could not search: {error.message}</p>}
{!data && loading && <p aria-busy="true">Searching...</p>}
{data && (
<>
<p className="muted">{data.total} results</p>
{/* The previous results stay on screen, dimmed, until the new ones arrive. */}
<ul className={`results ${loading || bounce.active ? "stale" : ""}`}>
{data.products.map((product) => (
<li key={product.id}>
<img src={product.thumbnail} alt="" width={48} height={48} loading="lazy" />
<span>{product.title}</span>
<small className="muted">${product.price}</small>
</li>
))}
</ul>
</>
)}
</section>
<article>
<header>
<strong>Sent queries</strong>
</header>
<ul className="log">
{sent.slice(0, 12).map((entry, index) => (
<li key={sent.length - index}>{entry}</li>
))}
</ul>
</article>
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/search hyper-fetch-react-search && cd hyper-fetch-react-search && npm install && npm run dev
What it shows
  1. The query is a query param. Each search term is its own request and cache key.
  2. bounce: true with bounceTime: 400 waits for a pause before sending the changed request.
  3. bounce.active tells the UI that a request is waiting for typing to stop.
  4. Previous results stay on screen while the next ones load, so the list does not flash.

How it works​

  1. api.ts defines searchProducts for /products/search with typed q, limit and select query params.
  2. App keeps the input value in state and passes searchProducts.setQueryParams({ q: query, ... }) to useFetch.
  3. The hook options { bounce: true, bounceType: "debounce", bounceTime: 400 } delay every change of the request. Each new keystroke restarts the 400 ms timer, so typing "laptop" sends one request for q="laptop". The first request on mount is never delayed.
  4. While the timer runs, bounce.active is true and the status shows "waiting for typing to stop".
  5. client.requestManager.events.onRequestStart counts every request the client sends. Turn the switch off and type again: every keystroke becomes a request.
  6. keepPreviousData is "auto" by default, which keeps the previous data when only query params change. The old results stay on screen, dimmed, until the new ones arrive.
// `select` is a dummyjson query param: the API returns only these fields.
const { data, loading, bounce } = useFetch(searchProducts.setQueryParams({ q: query, limit: 8, select: "title" }), {
bounce: true,
bounceTime: 400,
});

bounceType: "throttle" is the other mode: it sends at most one request per bounceTime while the input keeps changing, which suits live previews more than search.

When to use it
  • Search boxes, filters and autocomplete inputs that change on every keystroke.
  • Any input where only the settled value matters to the server.

Summary

You built search as you type with one useFetch call. bounce turned a request per keystroke into a request per pause, and the counters showed the difference.