AI Hints
Home›React Tutorial›Concurrent React
React · Lesson 71 of 120

useDeferredValue

Lagging on purpose.

⏱ 2 min read▶ Video at 59:13🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Sometimes you don't control the update, you just receive a value. Use deferred value gives you a copy that's allowed to lag behind, while the urgent parts update first.

  • You receive a value
  • A lagging copy
  • Urgent first

Instant typing, slower results

Typing should always feel instant, even if the results are slow. Use deferred value gives a copy of the query that's allowed to lag behind. The input uses the real query, so it updates straight away. The slow results use the deferred one, and fade while they catch up. We search for trail. Run it.

App.jsxjsx
import { useState, useDeferredValue, memo } from "react";
const Results = memo(function Results({ query }) {
  const start = performance.now();
  while (performance.now() - start < 100) {} // pretend this is slow
  const all = ["Trail 500", "City 200", "Volt 7", "Helmet", "Lights"];
  return <ul>{all.filter(p => p.toLowerCase().includes(query)).map(p => <li key={p}>{p}</li>)}</ul>;
});
export default function App() {
  const [query, setQuery] = useState("");
  const deferred = useDeferredValue(query);
  return (<div>
    <input id="q" value={query} onChange={e => setQuery(e.target.value.toLowerCase())} placeholder="Search" />
    <div style={{ opacity: query !== deferred ? 0.5 : 1 }}><Results query={deferred} /></div>
  </div>);
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"type": "#q", "text": "trail"}, {"wait": 500}]

Summary

Use deferred value lets slow parts lag behind, while urgent parts stay instant. Next, suspense and lazy.

Key takeaways
  • useDeferredValue
  • Instant input
  • Results catch up
Next up: Suspense and lazy — load parts later