javascript 43 lines · 7 steps

Keeping search input snappy with useDeferredValue in React

useDeferredValue lets a React search box stay responsive by filtering against a lagging copy of the query.

Explained by highlit
1import { useDeferredValue, useMemo, useState } from "react";
2 
3function ProductSearch({ products }) {
4 const [query, setQuery] = useState("");
5 const deferredQuery = useDeferredValue(query);
6 const isStale = query !== deferredQuery;
7 
8 const results = useMemo(() => {
9 const needle = deferredQuery.trim().toLowerCase();
10 if (!needle) return products;
11 return products.filter((p) =>
12 p.name.toLowerCase().includes(needle) ||
13 p.sku.toLowerCase().includes(needle) ||
14 p.tags.some((tag) => tag.toLowerCase().includes(needle))
15 );
16 }, [products, deferredQuery]);
17 
18 return (
19 <div className="product-search">
20 <input
21 type="search"
22 value={query}
23 placeholder="Search products…"
24 onChange={(e) => setQuery(e.target.value)}
25 aria-label="Search products"
26 />
27 <ul
28 className="results"
29 style={{ opacity: isStale ? 0.5 : 1, transition: "opacity 0.2s" }}
30 >
31 {results.map((product) => (
32 <li key={product.id}>
33 <span className="name">{product.name}</span>
34 <span className="sku">{product.sku}</span>
35 <span className="price">${product.price.toFixed(2)}</span>
36 </li>
37 ))}
38 </ul>
39 </div>
40 );
41}
42 
43export default ProductSearch;
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1useDeferredValue lets urgent updates like typing render immediately while expensive derived work catches up.
  2. 2Comparing the live value to its deferred copy gives you a free signal for showing stale UI.
  3. 3Memoizing filtering on the deferred value ensures the heavy work only reruns when the lagging query settles.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Keeping search input snappy with useDeferredValue in React — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code