JavaScript and React course Β· Module 9: Modern React Hooks
useDeferredValue - deferred values for performance
In this lesson3
In the useTransition lesson, you were the one deciding which state change was less urgent. But what if the value comes from props, from a library or from someone else's hook, and you have no access to its setter? The ship's radar reports a new position every fraction of a second, and the heavy galaxy map cannot keep up with drawing.
The useDeferredValue hook complements useTransition, allowing you to "defer" a value so that React can treat updates as less urgent. It is particularly useful when you want to keep the UI responsive while rendering heavy components.
useDeferredValue Basics
1. Syntax and basic usage
You pass any value to the hook, and it returns a "lagging" copy of it. On a change, React first renders the screen with the old copy, then does the new render in the background and can interrupt it. In a search box it looks like this:
import { useDeferredValue, useState } from 'react';
function SearchApp() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<div>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
{/* Input updates immediately */}
<p>Current query: {query}</p>
{/* List uses the deferred value */}
<SearchResults query={deferredQuery} />
</div>
);
}
function SearchResults({ query }) {
// Heavy computations with deferred value
const results = performHeavySearch(query);
return (
<div>
<p>Results for: "{query}"</p>
<ul>
{results.map(result => (
<li key={result.id}>{result.title}</li>
))}
</ul>
</div>
);
}
function performHeavySearch(query) {
// Simulation of heavy computations
const items = [];
for (let i = 0; i < 5000; i++) {
if (`Item ${i}`.toLowerCase().includes(query.toLowerCase())) {
items.push({ id: i, title: `Item ${i}` });
}
}
return items;
}The field and the "Current query" text read the fresh query, while the list gets deferredQuery. There is a catch, pointed out by react.dev: this optimization only works when the heavy component is wrapped in memo. Here SearchResults has no memo, so during the urgent render it still recomputes the results, just for the old value. We will fix that in section 3.
2. Difference between useDeferredValue and useTransition
Let's compare two ways of achieving the same effect. In the first we defer a value, in the second we split the state into urgent and transitional ourselves:
import { useDeferredValue, useTransition, useState } from 'react';
// Approach 1: useDeferredValue
function DeferredValueExample() {
const [input, setInput] = useState('');
const deferredInput = useDeferredValue(input);
return (
<div>
<h3>useDeferredValue</h3>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<HeavyComponent text={deferredInput} />
</div>
);
}
// Approach 2: useTransition
function TransitionExample() {
const [input, setInput] = useState('');
const [deferredInput, setDeferredInput] = useState('');
const [isPending, startTransition] = useTransition();
const handleChange = (value) => {
setInput(value); // Immediate update
startTransition(() => {
setDeferredInput(value); // Deferred update
});
};
return (
<div>
<h3>useTransition</h3>
<input
value={input}
onChange={(e) => handleChange(e.target.value)}
/>
{isPending && <div>Updating...</div>}
<HeavyComponent text={deferredInput} />
</div>
);
}
Both components behave similarly, but useTransition needs access to the place where state is updated and gives you an isPending flag. useDeferredValue, on the other hand, only needs the value. Here is the shared heavy component and both versions side by side:
function HeavyComponent({ text }) {
// Simulation of heavy rendering
const items = [];
for (let i = 0; i < 1000; i++) {
items.push(`${text} - element ${i}`);
}
return (
<div style={{ height: '200px', overflow: 'auto' }}>
{items.map((item, index) => (
<div key={index} style={{ padding: '2px' }}>
{item}
</div>
))}
</div>
);
}
// Comparison of both approaches
function ComparisonDemo() {
return (
<div style={{ display: 'flex', gap: '20px' }}>
<div style={{ flex: 1 }}>
<DeferredValueExample />
</div>
<div style={{ flex: 1 }}>
<TransitionExample />
</div>
</div>
);
}My recommendation: if you have access to the setter, usually choose useTransition. If you receive a ready-made value from props or an external hook, reach for useDeferredValue.
3. Working with memo for optimization
Now a version where deferring really works. The list is wrapped in memo, so React skips its render as long as its props do not change:
import { useDeferredValue, useState, useMemo, memo } from 'react';
// Component optimized with memo
const OptimizedList = memo(function OptimizedList({ items, highlightTerm }) {
console.log('OptimizedList renders for:', highlightTerm);
return (
<div style={{ height: '300px', overflow: 'auto', border: '1px solid #ddd' }}>
{items.map(item => (
<div
key={item.id}
style={{
padding: '8px',
borderBottom: '1px solid #eee',
backgroundColor: item.id % 2 === 0 ? '#f9f9f9' : '#fff'
}}
>
<strong>
{highlightText(item.title, highlightTerm)}
</strong>
<div style={{ fontSize: '14px', color: '#666' }}>
{highlightText(item.description, highlightTerm)}
</div>
</div>
))}
</div>
);
});
The console.log message lets you check when the list actually renders. The second part is the search component with its data and a "staleness" flag:
function SearchWithOptimization() {
const [searchTerm, setSearchTerm] = useState('');
const deferredSearchTerm = useDeferredValue(searchTerm);
// Generating data
const allItems = useMemo(() => generateSearchData(2000), []);
// Filtering with deferred value
const filteredItems = useMemo(() => allItems.filter(item =>
item.title.toLowerCase().includes(deferredSearchTerm.toLowerCase()) ||
item.description.toLowerCase().includes(deferredSearchTerm.toLowerCase())
), [allItems, deferredSearchTerm]);
const isStale = searchTerm !== deferredSearchTerm;
return (
<div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
<h2>Search with useDeferredValue</h2>
<input
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
style={{
width: '100%',
padding: '12px',
fontSize: '16px',
border: '2px solid #ddd',
borderRadius: '8px',
marginBottom: '10px'
}}
/>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '10px',
fontSize: '14px'
}}>
<span>
Found {filteredItems.length} results
{deferredSearchTerm && ` for "${deferredSearchTerm}"`}
</span>
{isStale && (
<span style={{ color: '#007bff', fontStyle: 'italic' }}>
Updating...
</span>
)}
</div>
<div style={{ opacity: isStale ? 0.7 : 1, transition: 'opacity 0.2s' }}>
<OptimizedList
items={filteredItems}
highlightTerm={deferredSearchTerm}
/>
</div>
</div>
);
}
function generateSearchData(count) {
const categories = ['Electronics', 'Books', 'Clothing', 'Home', 'Sports'];
const adjectives = ['Modern', 'Classic', 'Premium', 'Budget', 'Universal'];
return Array.from({ length: count }, (_, i) => ({
id: i,
title: `${adjectives[i % adjectives.length]} Product ${i + 1}`,
description: `Product description from the ${categories[i % categories.length]} category. High-quality item.`,
category: categories[i % categories.length],
price: Math.floor(Math.random() * 1000) + 50
}));
}
function highlightText(text, term) {
if (!term) return text;
const regex = new RegExp(`(${term})`, 'gi');
const parts = text.split(regex);
return parts.map((part, index) =>
part.toLowerCase() === term.toLowerCase() ? (
<mark key={index} style={{ backgroundColor: '#ffeb3b', padding: '2px' }}>
{part}
</mark>
) : part
);
}The comparison searchTerm !== deferredSearchTerm tells us the screen still shows old results, so we dim the list. We keep the data and the filtering in useMemo. Without it, every render would create a new filteredItems array, memo would always see new props and skip nothing. Since React 19 the hook also takes a second argument, useDeferredValue(value, initialValue), the value used during the initial render.
Advanced patterns with useDeferredValue
1. Adaptive loading with fallback
A deferred value also helps when switching tabs. A click highlights the new tab immediately, and the content catches up a moment later:
import { useDeferredValue, useState, Suspense } from 'react';
function AdaptiveLoadingDemo() {
const [selectedTab, setSelectedTab] = useState('popular');
const deferredTab = useDeferredValue(selectedTab);
const tabs = [
{ id: 'popular', label: 'Popular' },
{ id: 'newest', label: 'Newest' },
{ id: 'trending', label: 'Trending' }
];
return (
<div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
<h2>Adaptive Loading with useDeferredValue</h2>
{/* Tab Navigation */}
<div style={{
display: 'flex',
marginBottom: '20px',
borderBottom: '1px solid #ddd'
}}>
{tabs.map(tab => (
<button
key={tab.id}
onClick={() => setSelectedTab(tab.id)}
style={{
padding: '12px 20px',
border: 'none',
backgroundColor: selectedTab === tab.id ? '#007bff' : 'transparent',
color: selectedTab === tab.id ? 'white' : '#007bff',
cursor: 'pointer',
borderRadius: '8px 8px 0 0',
marginRight: '5px',
fontSize: '16px'
}}
>
{tab.label}
</button>
))}
</div>
{/* Content with deferred loading */}
<div style={{ position: 'relative' }}>
{/* Show loading state when tab is changing */}
{selectedTab !== deferredTab && (
<div style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(255, 255, 255, 0.8)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 1,
borderRadius: '8px'
}}>
<div style={{
padding: '20px',
backgroundColor: 'white',
borderRadius: '8px',
boxShadow: '0 2px 10px rgba(0,0,0,0.1)'
}}>
Loading content...
</div>
</div>
)}
<Suspense fallback={<TabContentSkeleton />}>
<TabContent tab={deferredTab} />
</Suspense>
</div>
</div>
);
}
The "Loading content..." overlay appears when selectedTab and deferredTab differ. Below are the content component, the skeleton and the data:
function TabContent({ tab }) {
// Simulation of heavy data loading
const content = generateTabContent(tab);
return (
<div style={{
minHeight: '400px',
padding: '20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px'
}}>
<h3>Tab content: {tab}</h3>
<div style={{ display: 'grid', gap: '15px' }}>
{content.map(item => (
<div
key={item.id}
style={{
padding: '15px',
backgroundColor: 'white',
borderRadius: '6px',
boxShadow: '0 1px 3px rgba(0,0,0,0.1)'
}}
>
<h4 style={{ margin: '0 0 8px 0', color: '#333' }}>
{item.title}
</h4>
<p style={{ margin: 0, color: '#666', fontSize: '14px' }}>
{item.description}
</p>
<div style={{
marginTop: '8px',
fontSize: '12px',
color: '#999'
}}>
{item.date} β’ {item.views} views
</div>
</div>
))}
</div>
</div>
);
}
function TabContentSkeleton() {
return (
<div style={{
minHeight: '400px',
padding: '20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px'
}}>
<div style={{
height: '24px',
backgroundColor: '#e9ecef',
borderRadius: '4px',
marginBottom: '20px',
width: '200px'
}} />
{Array.from({ length: 5 }).map((_, i) => (
<div
key={i}
style={{
padding: '15px',
backgroundColor: 'white',
borderRadius: '6px',
marginBottom: '15px',
boxShadow: '0 1px 3px rgba(0,0,0,0.1)'
}}
>
<div style={{
height: '18px',
backgroundColor: '#e9ecef',
borderRadius: '4px',
marginBottom: '8px',
width: '70%'
}} />
<div style={{
height: '14px',
backgroundColor: '#f1f3f4',
borderRadius: '4px',
marginBottom: '4px'
}} />
<div style={{
height: '14px',
backgroundColor: '#f1f3f4',
borderRadius: '4px',
width: '60%'
}} />
</div>
))}
</div>
);
}
function generateTabContent(tab) {
const contentMap = {
popular: [
{ id: 1, title: 'Most popular article', description: 'This article was the most popular this week.', date: '2024-01-15', views: 15420 },
{ id: 2, title: 'Second in ranking', description: 'Great material that earned reader recognition.', date: '2024-01-14', views: 12380 },
{ id: 3, title: 'Top 3 popularity', description: 'Also a very interesting article with a high rating.', date: '2024-01-13', views: 9560 }
],
newest: [
{ id: 4, title: 'Latest post', description: 'Freshly published blog material.', date: '2024-01-16', views: 245 },
{ id: 5, title: 'Yesterday\'s article', description: 'Published yesterday, already gaining popularity.', date: '2024-01-15', views: 1230 },
{ id: 6, title: 'From 2 days ago', description: 'Still relevant and valuable material.', date: '2024-01-14', views: 2100 }
],
trending: [
{ id: 7, title: 'Viral on social media', description: 'This article is taking social media by storm!', date: '2024-01-12', views: 25600 },
{ id: 8, title: 'Rising popularity', description: 'Quickly gaining popularity.', date: '2024-01-11', views: 8970 },
{ id: 9, title: 'Trend of the week', description: 'The main trend of this week in our industry.', date: '2024-01-10', views: 14520 }
]
};
return contentMap[tab] || [];
}Note that TabContent is synchronous here, so you will only see the TabContentSkeleton fallback when the component really suspends, for example while reading data through Suspense. With data loaded that way, useDeferredValue keeps showing the old content instead of the fallback.
2. Several filters at once
Several filters at once are a good candidate for several deferred values. First the state, the deferred copies and the memoized filtering:
import { useDeferredValue, useState, useMemo } from 'react';
function SmartFilteringDemo() {
const [searchQuery, setSearchQuery] = useState('');
const [priceRange, setPriceRange] = useState([0, 1000]);
const [category, setCategory] = useState('all');
// Deferred values for heavy operations
const deferredQuery = useDeferredValue(searchQuery);
const deferredPriceRange = useDeferredValue(priceRange);
const deferredCategory = useDeferredValue(category);
// Check if filtering is in progress
const isFiltering =
searchQuery !== deferredQuery ||
priceRange !== deferredPriceRange ||
category !== deferredCategory;
const products = useMemo(() => generateProducts(1000), []);
// Filtering with deferred values
const filteredProducts = useMemo(() => {
return products.filter(product => {
const matchesSearch = product.name.toLowerCase().includes(deferredQuery.toLowerCase()) ||
product.description.toLowerCase().includes(deferredQuery.toLowerCase());
const matchesPrice = product.price >= deferredPriceRange[0] &&
product.price <= deferredPriceRange[1];
const matchesCategory = deferredCategory === 'all' ||
product.category === deferredCategory;
return matchesSearch && matchesPrice && matchesCategory;
});
}, [products, deferredQuery, deferredPriceRange, deferredCategory]);
The isFiltering flag compares every pair of values. The priceRange array is compared by reference, which works because every slider change creates a new array. Now the filter panel and the results grid:
return (
<div style={{ maxWidth: '1200px', margin: '0 auto', padding: '20px' }}>
<h2>Smart Filtering with useDeferredValue</h2>
<div style={{
display: 'grid',
gridTemplateColumns: '300px 1fr',
gap: '20px'
}}>
{/* Filters Sidebar */}
<div style={{
padding: '20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px',
height: 'fit-content'
}}>
<h3 style={{ marginTop: 0 }}>Filters</h3>
{/* Search Filter */}
<div style={{ marginBottom: '20px' }}>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
Search:
</label>
<input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
style={{
width: '100%',
padding: '8px',
border: '1px solid #ddd',
borderRadius: '4px'
}}
/>
</div>
{/* Category Filter */}
<div style={{ marginBottom: '20px' }}>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
Category:
</label>
<select
value={category}
onChange={(e) => setCategory(e.target.value)}
style={{
width: '100%',
padding: '8px',
border: '1px solid #ddd',
borderRadius: '4px'
}}
>
<option value="all">All</option>
<option value="Electronics">Electronics</option>
<option value="Books">Books</option>
<option value="Clothing">Clothing</option>
<option value="Home">Home</option>
</select>
</div>
{/* Price Range Filter */}
<div style={{ marginBottom: '20px' }}>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
Price: {priceRange[0]} - {priceRange[1]} $
</label>
<input
type="range"
min="0"
max="1000"
value={priceRange[1]}
onChange={(e) => setPriceRange([priceRange[0], parseInt(e.target.value)])}
style={{ width: '100%' }}
/>
</div>
{/* Filter Status */}
<div style={{
padding: '10px',
backgroundColor: isFiltering ? '#fff3cd' : '#d4edda',
borderRadius: '4px',
fontSize: '14px',
textAlign: 'center'
}}>
{isFiltering ? (
<span>Filtering...</span>
) : (
<span>Done</span>
)}
</div>
</div>
{/* Results */}
<div>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '20px'
}}>
<h3 style={{ margin: 0 }}>
Products ({filteredProducts.length})
</h3>
{isFiltering && (
<span style={{ color: '#007bff', fontSize: '14px' }}>
Updating results...
</span>
)}
</div>
<div style={{
opacity: isFiltering ? 0.7 : 1,
transition: 'opacity 0.3s',
display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))',
gap: '15px'
}}>
{filteredProducts.slice(0, 20).map(product => (
<div
key={product.id}
style={{
padding: '15px',
backgroundColor: 'white',
border: '1px solid #e9ecef',
borderRadius: '8px',
boxShadow: '0 1px 3px rgba(0,0,0,0.1)'
}}
>
<h4 style={{ margin: '0 0 8px 0', fontSize: '16px' }}>
{highlightText(product.name, deferredQuery)}
</h4>
<p style={{
margin: '0 0 8px 0',
fontSize: '14px',
color: '#666',
lineHeight: '1.4'
}}>
{highlightText(product.description, deferredQuery)}
</p>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
fontSize: '14px'
}}>
<span style={{
backgroundColor: '#e9ecef',
padding: '2px 6px',
borderRadius: '4px',
fontSize: '12px'
}}>
{product.category}
</span>
<span style={{
fontWeight: 'bold',
color: '#007bff',
fontSize: '16px'
}}>
${product.price}
</span>
</div>
</div>
))}
</div>
{filteredProducts.length === 0 && (
<div style={{
textAlign: 'center',
padding: '40px',
color: '#666'
}}>
No products match the criteria
</div>
)}
</div>
</div>
</div>
);
}
The controls read fresh values, while the product grid uses the deferred ones. Finally, the data generator and the highlighting:
function generateProducts(count) {
const categories = ['Electronics', 'Books', 'Clothing', 'Home'];
const adjectives = ['Premium', 'Classic', 'Modern', 'Vintage', 'Professional'];
const nouns = ['Device', 'Tool', 'Item', 'Product', 'Gadget'];
return Array.from({ length: count }, (_, i) => ({
id: i,
name: `${adjectives[i % adjectives.length]} ${nouns[i % nouns.length]} ${i + 1}`,
description: `High-quality ${categories[i % categories.length].toLowerCase()} item with excellent features and durability.`,
category: categories[i % categories.length],
price: Math.floor(Math.random() * 950) + 50
}));
}
function highlightText(text, term) {
if (!term) return text;
const regex = new RegExp(`(${term})`, 'gi');
const parts = text.split(regex);
return parts.map((part, index) =>
part.toLowerCase() === term.toLowerCase() ? (
<mark key={index} style={{ backgroundColor: '#ffeb3b', padding: '1px' }}>
{part}
</mark>
) : part
);
}Unlike debouncing, there is no fixed delay here: React defers the render only as long as the device needs.
Best practices with useDeferredValue
1. When to use useDeferredValue
The examples below show where deferring pays off and where it only adds work. The key is the render cost of the component that receives the deferred value:
// GOOD - Heavy lists and filtering
function ProductSearch() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<HeavyProductList searchTerm={deferredQuery} />
</>
);
}
// GOOD - Rendering charts
function ChartDashboard() {
const [dateRange, setDateRange] = useState([startDate, endDate]);
const deferredDateRange = useDeferredValue(dateRange);
return (
<>
<DateRangePicker onChange={setDateRange} />
<ExpensiveChart dateRange={deferredDateRange} />
</>
);
}
// BAD - Simple operations
function SimpleCounter() {
const [count, setCount] = useState(0);
const deferredCount = useDeferredValue(count); // Unnecessary!
return <div>{deferredCount}</div>;
}The counter in SimpleCounter renders a single number, so deferring speeds nothing up and only adds a second render.
2. Combining with other hooks
In the data table we combine useDeferredValue with useMemo and useCallback. Filtering and sorting depend only on the deferred values:
import { useDeferredValue, useState, useMemo, useCallback } from 'react';
function OptimizedDataTable() {
const [searchTerm, setSearchTerm] = useState('');
const [sortConfig, setSortConfig] = useState({ field: 'name', direction: 'asc' });
const deferredSearchTerm = useDeferredValue(searchTerm);
const deferredSortConfig = useDeferredValue(sortConfig);
const data = useMemo(() => generateLargeDataset(5000), []);
// Memoized filtering and sorting
const processedData = useMemo(() => {
let filtered = data;
if (deferredSearchTerm) {
filtered = data.filter(item =>
item.name.toLowerCase().includes(deferredSearchTerm.toLowerCase())
);
}
return [...filtered].sort((a, b) => {
const direction = deferredSortConfig.direction === 'asc' ? 1 : -1;
return String(a[deferredSortConfig.field])
.localeCompare(String(b[deferredSortConfig.field]), undefined, { numeric: true }) * direction;
});
}, [data, deferredSearchTerm, deferredSortConfig]);
const handleSort = useCallback((field) => {
setSortConfig(prev => ({
field,
direction: prev.field === field && prev.direction === 'asc' ? 'desc' : 'asc'
}));
}, []);
const isStale = searchTerm !== deferredSearchTerm || sortConfig !== deferredSortConfig;
return (
<div>
<input
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<table style={{ opacity: isStale ? 0.7 : 1 }}>
<thead>
<tr>
<th onClick={() => handleSort('name')}>Name</th>
<th onClick={() => handleSort('category')}>Category</th>
<th onClick={() => handleSort('price')}>Price</th>
</tr>
</thead>
<tbody>
{processedData.slice(0, 50).map(item => (
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.category}</td>
<td>{item.price}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}We sort a copy, [...filtered], because sort mutates the array in place and without a copy it would corrupt the memoized data. Comparing through String with the numeric option also handles the price column, which holds numbers.
3. What to avoid
The last example shows too much of a good thing. Three separate deferred values for a simple form only complicate the code:
// BAD - Overuse
function OverusedDeferred() {
const [name, setName] = useState('');
const [age, setAge] = useState(0);
const [email, setEmail] = useState('');
// Not every value needs deferred!
const deferredName = useDeferredValue(name);
const deferredAge = useDeferredValue(age);
const deferredEmail = useDeferredValue(email);
return <SimpleForm name={deferredName} age={deferredAge} email={deferredEmail} />;
}
// BETTER - Selective use
function BetterApproach() {
const [formData, setFormData] = useState({ name: '', age: 0, email: '' });
const deferredFormData = useDeferredValue(formData);
return <HeavyValidationForm data={deferredFormData} />;
}It is better to defer a single object passed to a truly heavy component.
useDeferredValue is an elegant way to improve the performance of React applications without complex state management. It allows you to keep critical UI elements responsive while performing heavy operations in the background.
Measure before you optimize: you will learn list virtualization in the next lesson. Remember: a deferred value is a radar echo that the galaxy map reads as soon as the pilot finishes the maneuver.
Code for this lesson: App.jsx
import { useDeferredValue, useState, memo, useMemo } from 'react';
// Simulation of heavy operation - rendering many elements
function generateItems(count, filter = '') {
const items = [];
for (let i = 0; i < count; i++) {
const name = `Product ${i + 1}`;
const category = ['Electronics', 'Books', 'Clothing', 'Home', 'Sports'][i % 5];
if (filter === '' ||
name.toLowerCase().includes(filter.toLowerCase()) ||
category.toLowerCase().includes(filter.toLowerCase())) {
items.push({
id: i,
name,
category,
price: Math.floor(Math.random() * 1000) + 10,
rating: (Math.random() * 5).toFixed(1),
inStock: Math.random() > 0.2
});
}
}
return items;
}
// Component optimized with memo
const ProductList = memo(function ProductList({ items, isStale }) {
// Simulation of heavy computations
const processedItems = useMemo(() => {
return items.map(item => ({
...item,
displayPrice: `${item.price} credits`,
ratingStars: 'β'.repeat(Math.floor(item.rating)) + 'β'.repeat(5 - Math.floor(item.rating))
}));
}, [items]);
return (
<div style={{
opacity: isStale ? 0.6 : 1,
transition: 'opacity 0.2s',
height: '500px',
overflow: 'auto',
border: '1px solid #ddd',
borderRadius: '8px',
backgroundColor: '#fff'
}}>
{isStale && (
<div style={{
position: 'sticky',
top: 0,
backgroundColor: '#fff3cd',
padding: '8px 16px',
borderBottom: '1px solid #ffeaa7',
fontSize: '14px',
color: '#856404'
}}>
Updating results...
</div>
)}
{processedItems.length === 0 ? (
<div style={{
padding: '40px',
textAlign: 'center',
color: '#666'
}}>
No products matching criteria
</div>
) : (
<div style={{ padding: '16px' }}>
<div style={{
marginBottom: '16px',
fontSize: '14px',
color: '#666',
borderBottom: '1px solid #eee',
paddingBottom: '8px'
}}>
Found {processedItems.length} products
</div>
<div style={{
display: 'grid',
gap: '16px',
gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))'
}}>
{processedItems.map(item => (
<div
key={item.id}
style={{
padding: '16px',
border: '1px solid #e9ecef',
borderRadius: '8px',
backgroundColor: '#f8f9fa'
}}
>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
marginBottom: '8px'
}}>
<h3 style={{
margin: 0,
fontSize: '16px',
color: '#333'
}}>
{item.name}
</h3>
<span style={{
fontSize: '12px',
padding: '4px 8px',
backgroundColor: '#007bff',
color: 'white',
borderRadius: '12px'
}}>
{item.category}
</span>
</div>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '8px'
}}>
<span style={{
fontSize: '18px',
fontWeight: 'bold',
color: '#28a745'
}}>
{item.displayPrice}
</span>
<div style={{ fontSize: '14px', color: '#ffc107' }}>
{item.ratingStars} ({item.rating})
</div>
</div>
<div style={{
fontSize: '12px',
color: item.inStock ? '#28a745' : '#dc3545',
fontWeight: 'bold'
}}>
{item.inStock ? 'In stock' : 'Out of stock'}
</div>
</div>
))}
</div>
</div>
)}
</div>
);
});
function DeferredValueDemo() {
const [query, setQuery] = useState('');
const [category, setCategory] = useState('');
const [sortBy, setSortBy] = useState('name');
// DEFERRED VALUES - will update with a delay
const deferredQuery = useDeferredValue(query);
const deferredCategory = useDeferredValue(category);
const deferredSortBy = useDeferredValue(sortBy);
// Check if values are stale (outdated)
const isStale = deferredQuery !== query ||
deferredCategory !== category ||
deferredSortBy !== sortBy;
// Generating results based on DEFERRED values
const results = useMemo(() => {
let items = generateItems(8000, deferredQuery);
// Filter by category
if (deferredCategory) {
items = items.filter(item =>
item.category.toLowerCase().includes(deferredCategory.toLowerCase())
);
}
// Sorting
items.sort((a, b) => {
switch (deferredSortBy) {
case 'price':
return a.price - b.price;
case 'rating':
return b.rating - a.rating;
case 'name':
default:
return a.name.localeCompare(b.name);
}
});
return items;
}, [deferredQuery, deferredCategory, deferredSortBy]);
return (
<div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
<h2>useDeferredValue Demo - Online Shop</h2>
<div style={{
display: 'flex',
gap: '16px',
marginBottom: '20px',
flexWrap: 'wrap'
}}>
<div style={{ flex: '1', minWidth: '200px' }}>
<label style={{
display: 'block',
marginBottom: '4px',
fontSize: '14px',
fontWeight: 'bold'
}}>
Search product:
</label>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Type product name..."
style={{
width: '100%',
padding: '10px',
fontSize: '16px',
border: '2px solid #ddd',
borderRadius: '6px',
outline: 'none',
boxSizing: 'border-box'
}}
/>
</div>
<div style={{ flex: '1', minWidth: '150px' }}>
<label style={{
display: 'block',
marginBottom: '4px',
fontSize: '14px',
fontWeight: 'bold'
}}>
Category:
</label>
<select
value={category}
onChange={(e) => setCategory(e.target.value)}
style={{
width: '100%',
padding: '10px',
fontSize: '16px',
border: '2px solid #ddd',
borderRadius: '6px',
outline: 'none',
backgroundColor: 'white'
}}
>
<option value="">All categories</option>
<option value="Electronics">Electronics</option>
<option value="Books">Books</option>
<option value="Clothing">Clothing</option>
<option value="Home">Home</option>
<option value="Sports">Sports</option>
</select>
</div>
<div style={{ flex: '1', minWidth: '150px' }}>
<label style={{
display: 'block',
marginBottom: '4px',
fontSize: '14px',
fontWeight: 'bold'
}}>
Sort by:
</label>
<select
value={sortBy}
onChange={(e) => setSortBy(e.target.value)}
style={{
width: '100%',
padding: '10px',
fontSize: '16px',
border: '2px solid #ddd',
borderRadius: '6px',
outline: 'none',
backgroundColor: 'white'
}}
>
<option value="name">Name</option>
<option value="price">Price</option>
<option value="rating">Rating</option>
</select>
</div>
</div>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '16px',
padding: '12px',
backgroundColor: '#e3f2fd',
borderRadius: '8px',
fontSize: '14px'
}}>
<div>
<strong>Filter status:</strong>
<ul style={{ margin: '4px 0', paddingLeft: '20px' }}>
<li>Search: "{query}" {deferredQuery !== query && '(updating...)'}</li>
<li>Category: {category || 'All'} {deferredCategory !== category && '(updating...)'}</li>
<li>Sort: {sortBy} {deferredSortBy !== sortBy && '(updating...)'}</li>
</ul>
</div>
<div style={{ textAlign: 'right' }}>
{isStale ? (
<span style={{ color: '#ff9800', fontWeight: 'bold' }}>
Updating results...
</span>
) : (
<span style={{ color: '#4caf50', fontWeight: 'bold' }}>
Results up to date
</span>
)}
</div>
</div>
<ProductList items={results} isStale={isStale} />
<div style={{
marginTop: '20px',
padding: '16px',
backgroundColor: '#f1f8e9',
borderRadius: '8px',
fontSize: '14px'
}}>
<strong>What to observe in this demo:</strong>
<ul style={{ margin: '10px 0', paddingLeft: '20px' }}>
<li><strong>Responsive inputs:</strong> All controls react immediately</li>
<li><strong>Deferred rendering:</strong> Product list updates with a delay</li>
<li><strong>Stale indicator:</strong> Visible when data is outdated</li>
<li><strong>Transparency:</strong> List becomes transparent during updates</li>
<li><strong>Memo optimization:</strong> Component does not re-render when props are identical</li>
</ul>
<div style={{
marginTop: '12px',
padding: '8px',
backgroundColor: '#fff3e0',
borderRadius: '4px'
}}>
<strong>Try this:</strong> Quickly change filters and see how React prioritizes
input responsiveness over product list rendering!
</div>
</div>
</div>
);
}
function ComparisonDemo() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
// Simulation of different handling approaches
const [version, setVersion] = useState('deferred');
const results = useMemo(() => {
const searchTerm = version === 'deferred' ? deferredQuery : query;
return generateItems(5000, searchTerm);
}, [version === 'deferred' ? deferredQuery : query, version]);
return (
<div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
<h2>Comparison: useDeferredValue vs no optimization</h2>
<div style={{
display: 'flex',
gap: '10px',
marginBottom: '20px',
padding: '16px',
backgroundColor: '#f8f9fa',
borderRadius: '8px'
}}>
<button
onClick={() => setVersion('deferred')}
style={{
padding: '10px 20px',
backgroundColor: version === 'deferred' ? '#28a745' : '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
With useDeferredValue
</button>
<button
onClick={() => setVersion('immediate')}
style={{
padding: '10px 20px',
backgroundColor: version === 'immediate' ? '#dc3545' : '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Without optimization
</button>
</div>
<div style={{ marginBottom: '20px' }}>
<label style={{
display: 'block',
marginBottom: '8px',
fontSize: '16px',
fontWeight: 'bold'
}}>
Search products:
</label>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Try typing fast and see the difference..."
style={{
width: '100%',
padding: '12px',
fontSize: '16px',
border: '2px solid #ddd',
borderRadius: '8px',
outline: 'none',
boxSizing: 'border-box'
}}
/>
<div style={{
marginTop: '8px',
fontSize: '14px',
color: '#666',
display: 'flex',
justifyContent: 'space-between'
}}>
<span>Current value: "{query}"</span>
<span>
{version === 'deferred' && deferredQuery !== query && (
<span style={{ color: '#ff9800' }}>
Rendering: "{deferredQuery}"
</span>
)}
</span>
</div>
</div>
<div style={{
height: '400px',
overflow: 'auto',
border: '1px solid #ddd',
borderRadius: '8px',
backgroundColor: '#fff'
}}>
{results.length === 0 ? (
<div style={{
padding: '40px',
textAlign: 'center',
color: '#666'
}}>
No results
</div>
) : (
results.slice(0, 100).map(item => (
<div
key={item.id}
style={{
padding: '12px',
borderBottom: '1px solid #eee',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}
>
<div>
<div style={{ fontWeight: 'bold' }}>{item.name}</div>
<div style={{ fontSize: '12px', color: '#666' }}>
{item.category}
</div>
</div>
<div style={{ fontWeight: 'bold', color: '#28a745' }}>
{item.price} credits
</div>
</div>
))
)}
</div>
<div style={{
marginTop: '16px',
padding: '12px',
backgroundColor: version === 'deferred' ? '#d4edda' : '#f8d7da',
borderRadius: '8px',
fontSize: '14px'
}}>
<strong>
{version === 'deferred' ? 'With useDeferredValue:' : 'Without optimization:'}
</strong>
<p style={{ margin: '8px 0' }}>
{version === 'deferred'
? 'Input stays responsive, list updates with a delay when typing fast.'
: 'Every change in input immediately renders the entire list, which can cause lagging.'
}
</p>
</div>
</div>
);
}
export default function App() {
const [activeDemo, setActiveDemo] = useState('shop');
return (
<div style={{ minHeight: '100vh', backgroundColor: '#f5f5f5' }}>
<nav style={{
backgroundColor: '#fff',
padding: '10px 0',
borderBottom: '1px solid #ddd',
marginBottom: '20px'
}}>
<div style={{
maxWidth: '1200px',
margin: '0 auto',
display: 'flex',
gap: '10px',
padding: '0 20px'
}}>
<button
onClick={() => setActiveDemo('shop')}
style={{
padding: '10px 20px',
backgroundColor: activeDemo === 'shop' ? '#007bff' : '#f8f9fa',
color: activeDemo === 'shop' ? 'white' : '#333',
border: '1px solid #ddd',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Online Shop
</button>
<button
onClick={() => setActiveDemo('comparison')}
style={{
padding: '10px 20px',
backgroundColor: activeDemo === 'comparison' ? '#007bff' : '#f8f9fa',
color: activeDemo === 'comparison' ? 'white' : '#333',
border: '1px solid #ddd',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Comparison
</button>
</div>
</nav>
{activeDemo === 'shop' ? <DeferredValueDemo /> : <ComparisonDemo />}
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Horizontal ordering
Arrange the syntax of the useDeferredValue hook:
- Horizontal ordering
Arrange the destructuring syntax of the useTransition hook: