Kurs JavaScript i React · Moduł 9: Nowoczesne hooki React
useDeferredValue - opóźnione wartości dla wydajności
W tej lekcji3
W lekcji o useTransition to Ty decydowałeś, która zmiana stanu jest mniej pilna. Co jednak, gdy wartość przychodzi z propsów, z biblioteki albo z cudzego hooka i nie masz dostępu do jej setera? Radar statku podaje nową pozycję co ułamek sekundy, a ciężka mapa galaktyki nie nadąża z rysowaniem.
Hook useDeferredValue to uzupełnienie useTransition, które pozwala na "opóźnienie" wartości, dzięki czemu React może traktować aktualizacje jako mniej pilne. Jest szczególnie przydatny, gdy chcemy zachować responsywność UI podczas renderowania ciężkich komponentów.
Podstawy useDeferredValue
1. Składnia i podstawowe użycie
Przekazujesz do hooka dowolną wartość, a on zwraca jej "spóźnioną" kopię. Przy zmianie React najpierw renderuje ekran ze starą kopią, a nowy render robi w tle i może go przerwać. W wyszukiwarce wygląda to tak:
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 aktualizuje się natychmiast */}
<p>Aktualne zapytanie: {query}</p>
{/* Lista używa opóźnionej wartości */}
<SearchResults query={deferredQuery} />
</div>
);
}
function SearchResults({ query }) {
// Ciężkie obliczenia z opóźnioną wartością
const results = performHeavySearch(query);
return (
<div>
<p>Wyniki dla: "{query}"</p>
<ul>
{results.map(result => (
<li key={result.id}>{result.title}</li>
))}
</ul>
</div>
);
}
function performHeavySearch(query) {
// Symulacja ciężkich obliczeń
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;
}Pole i napis "Aktualne zapytanie" czytają świeże query, a lista dostaje deferredQuery. Jest jednak haczyk, na który zwraca uwagę react.dev: ta optymalizacja działa tylko wtedy, gdy ciężki komponent jest owinięty w memo. Tutaj SearchResults nie ma memo, więc w pilnym renderze i tak liczy wyniki od nowa, tyle że dla starej wartości. Naprawimy to w sekcji 3.
2. Różnica między useDeferredValue a useTransition
Porównajmy dwa sposoby osiągnięcia tego samego efektu. W pierwszym opóźniamy wartość, w drugim sami rozdzielamy stan na pilny i przejściowy:
import { useDeferredValue, useTransition, useState } from 'react';
// Podejście 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>
);
}
// Podejście 2: useTransition
function TransitionExample() {
const [input, setInput] = useState('');
const [deferredInput, setDeferredInput] = useState('');
const [isPending, startTransition] = useTransition();
const handleChange = (value) => {
setInput(value); // Natychmiastowa aktualizacja
startTransition(() => {
setDeferredInput(value); // Opóźniona aktualizacja
});
};
return (
<div>
<h3>useTransition</h3>
<input
value={input}
onChange={(e) => handleChange(e.target.value)}
/>
{isPending && <div>Aktualizowanie...</div>}
<HeavyComponent text={deferredInput} />
</div>
);
}
Oba komponenty dają podobny efekt, ale useTransition wymaga dostępu do miejsca aktualizacji stanu i daje flagę isPending. Z kolei useDeferredValue wystarczy sama wartość. Oto wspólny ciężki komponent i zestawienie obu wersji obok siebie:
function HeavyComponent({ text }) {
// Symulacja ciężkiego renderowania
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>
);
}
// Porównanie obu podejść
function ComparisonDemo() {
return (
<div style={{ display: 'flex', gap: '20px' }}>
<div style={{ flex: 1 }}>
<DeferredValueExample />
</div>
<div style={{ flex: 1 }}>
<TransitionExample />
</div>
</div>
);
}Moja rekomendacja: jeśli masz dostęp do setera, zwykle wybierz useTransition. Jeśli dostajesz gotową wartość z props lub zewnętrznego hooka, sięgnij po useDeferredValue.
3. Współpraca z memo dla optymalizacji
Teraz wersja, w której opóźnienie naprawdę działa. Lista jest opakowana w memo, więc React pominie jej render, dopóki propsy się nie zmienią:
import { useDeferredValue, useState, useMemo, memo } from 'react';
// Komponent zoptymalizowany z memo
const OptimizedList = memo(function OptimizedList({ items, highlightTerm }) {
console.log('OptimizedList renderuje się dla:', 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>
);
});
Komunikat w console.log pozwala sprawdzić, kiedy lista faktycznie się renderuje. Druga część to komponent wyszukiwarki z danymi i flagą "nieaktualności":
function SearchWithOptimization() {
const [searchTerm, setSearchTerm] = useState('');
const deferredSearchTerm = useDeferredValue(searchTerm);
// Generowanie danych
const allItems = useMemo(() => generateSearchData(2000), []);
// Filtrowanie z opóźnioną wartością
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>Wyszukiwarka z 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>
Znaleziono {filteredItems.length} wyników
{deferredSearchTerm && ` dla "${deferredSearchTerm}"`}
</span>
{isStale && (
<span style={{ color: '#007bff', fontStyle: 'italic' }}>
Aktualizowanie...
</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 = ['Elektronika', 'Książki', 'Odzież', 'Dom', 'Sport'];
const adjectives = ['Nowoczesny', 'Klasyczny', 'Premium', 'Ekonomiczny', 'Uniwersalny'];
return Array.from({ length: count }, (_, i) => ({
id: i,
title: `${adjectives[i % adjectives.length]} Produkt ${i + 1}`,
description: `Opis produktu z kategorii ${categories[i % categories.length]}. Wysokiej jakości artykuł.`,
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
);
}Porównanie searchTerm !== deferredSearchTerm mówi, że ekran pokazuje jeszcze stare wyniki, więc przyciemniamy listę. Dane i filtrowanie trzymamy w useMemo. Bez tego każdy render tworzyłby nową tablicę filteredItems, a memo zawsze widziałby nowe propsy i nic by nie pominął. Od React 19 hook przyjmuje też drugi argument, useDeferredValue(value, initialValue), czyli wartość używaną przy pierwszym renderze.
Zaawansowane wzorce z useDeferredValue
1. Zakładki z opóźnioną treścią
Opóźniona wartość sprawdza się też przy przełączaniu zakładek. Kliknięcie od razu podświetla nową zakładkę, a treść dogania ją chwilę później:
import { useDeferredValue, useState, Suspense } from 'react';
function AdaptiveLoadingDemo() {
const [selectedTab, setSelectedTab] = useState('popular');
const deferredTab = useDeferredValue(selectedTab);
const tabs = [
{ id: 'popular', label: 'Popularne' },
{ id: 'newest', label: 'Najnowsze' },
{ id: 'trending', label: 'Trending' }
];
return (
<div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
<h2>Adaptive Loading z 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)'
}}>
Ładowanie zawartości...
</div>
</div>
)}
<Suspense fallback={<TabContentSkeleton />}>
<TabContent tab={deferredTab} />
</Suspense>
</div>
</div>
);
}
Nakładka "Ładowanie zawartości..." pojawia się, gdy selectedTab i deferredTab się różnią. Poniżej komponenty treści, szkieletu i dane:
function TabContent({ tab }) {
// Symulacja ciężkiego ładowania danych
const content = generateTabContent(tab);
return (
<div style={{
minHeight: '400px',
padding: '20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px'
}}>
<h3>Zawartość zakładki: {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} wyświetleń
</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: 'Najpopularniejszy artykuł', description: 'Ten artykuł cieszył się największą popularnością w tym tygodniu.', date: '2024-01-15', views: 15420 },
{ id: 2, title: 'Drugi w rankingu', description: 'Świetny materiał, który zdobył uznanie czytelników.', date: '2024-01-14', views: 12380 },
{ id: 3, title: 'Top 3 popularności', description: 'Również bardzo ciekawy artykuł z wysoką oceną.', date: '2024-01-13', views: 9560 }
],
newest: [
{ id: 4, title: 'Najnowszy post', description: 'Świeżo opublikowany materiał na blogu.', date: '2024-01-16', views: 245 },
{ id: 5, title: 'Wczorajszy artykuł', description: 'Opublikowany wczoraj, już zyskuje popularność.', date: '2024-01-15', views: 1230 },
{ id: 6, title: 'Sprzed 2 dni', description: 'Nadal aktualny i wartościowy materiał.', date: '2024-01-14', views: 2100 }
],
trending: [
{ id: 7, title: 'Viral na social media', description: 'Ten artykuł podbija social media!', date: '2024-01-12', views: 25600 },
{ id: 8, title: 'Rosnąca popularność', description: 'Szybko zyskuje na popularności.', date: '2024-01-11', views: 8970 },
{ id: 9, title: 'Trend tygodnia', description: 'Główny trend tego tygodnia w naszej branży.', date: '2024-01-10', views: 14520 }
]
};
return contentMap[tab] || [];
}Zwróć uwagę, że TabContent jest tu synchroniczny, więc fallback TabContentSkeleton zobaczysz dopiero wtedy, gdy komponent naprawdę się zawiesi, np. czytając dane przez Suspense. Przy danych ładowanych w ten sposób useDeferredValue dłużej pokazuje starą treść zamiast fallbacku.
2. Kilka filtrów naraz
Kilka filtrów naraz to dobry kandydat na kilka opóźnionych wartości. Najpierw stan, opóźnione kopie i memoizowane filtrowanie:
import { useDeferredValue, useState, useMemo } from 'react';
function SmartFilteringDemo() {
const [searchQuery, setSearchQuery] = useState('');
const [priceRange, setPriceRange] = useState([0, 1000]);
const [category, setCategory] = useState('all');
// Opóźnione wartości dla ciężkich operacji
const deferredQuery = useDeferredValue(searchQuery);
const deferredPriceRange = useDeferredValue(priceRange);
const deferredCategory = useDeferredValue(category);
// Sprawdzenie czy filtrowanie jest w toku
const isFiltering =
searchQuery !== deferredQuery ||
priceRange !== deferredPriceRange ||
category !== deferredCategory;
const products = useMemo(() => generateProducts(1000), []);
// Filtrowanie z opóźnionymi wartościami
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]);
Flaga isFiltering porównuje każdą parę wartości. Tablica priceRange jest porównywana po referencji, co działa, bo każda zmiana suwaka tworzy nową tablicę. Teraz panel filtrów i siatka wyników:
return (
<div style={{ maxWidth: '1200px', margin: '0 auto', padding: '20px' }}>
<h2>Smart Filtering z 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 }}>Filtry</h3>
{/* Search Filter */}
<div style={{ marginBottom: '20px' }}>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
Szukaj:
</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' }}>
Kategoria:
</label>
<select
value={category}
onChange={(e) => setCategory(e.target.value)}
style={{
width: '100%',
padding: '8px',
border: '1px solid #ddd',
borderRadius: '4px'
}}
>
<option value="all">Wszystkie</option>
<option value="Electronics">Elektronika</option>
<option value="Books">Książki</option>
<option value="Clothing">Odzież</option>
<option value="Home">Dom</option>
</select>
</div>
{/* Price Range Filter */}
<div style={{ marginBottom: '20px' }}>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
Cena: {priceRange[0]} - {priceRange[1]} zł
</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>Filtrowanie...</span>
) : (
<span>Gotowe</span>
)}
</div>
</div>
{/* Results */}
<div>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '20px'
}}>
<h3 style={{ margin: 0 }}>
Produkty ({filteredProducts.length})
</h3>
{isFiltering && (
<span style={{ color: '#007bff', fontSize: '14px' }}>
Aktualizowanie wyników...
</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} zł
</span>
</div>
</div>
))}
</div>
{filteredProducts.length === 0 && (
<div style={{
textAlign: 'center',
padding: '40px',
color: '#666'
}}>
Brak produktów spełniających kryteria
</div>
)}
</div>
</div>
</div>
);
}
Pola sterujące czytają świeże wartości, a siatka produktów korzysta z opóźnionych. Na koniec generator danych i podświetlanie:
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
);
}W przeciwieństwie do debouncingu nie ma tu stałego opóźnienia: React opóźnia render tylko tak długo, jak wymaga tego urządzenie.
Najlepsze praktyki z useDeferredValue
1. Kiedy używać useDeferredValue
Poniższe przykłady pokazują, gdzie opóźnienie się opłaca, a gdzie tylko dokłada pracy. Kluczem jest koszt renderu komponentu, który dostaje opóźnioną wartość:
// DOBRZE - Ciężkie listy i filtrowanie
function ProductSearch() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<HeavyProductList searchTerm={deferredQuery} />
</>
);
}
// DOBRZE - Renderowanie wykresów
function ChartDashboard() {
const [dateRange, setDateRange] = useState([startDate, endDate]);
const deferredDateRange = useDeferredValue(dateRange);
return (
<>
<DateRangePicker onChange={setDateRange} />
<ExpensiveChart dateRange={deferredDateRange} />
</>
);
}
// ŹLE - Proste operacje
function SimpleCounter() {
const [count, setCount] = useState(0);
const deferredCount = useDeferredValue(count); // Niepotrzebne!
return <div>{deferredCount}</div>;
}Licznik w SimpleCounter renderuje jedną liczbę, więc opóźnianie niczego nie przyspieszy, a tylko doda drugi render.
2. Łączenie z innymi hookami
W tabeli danych łączymy useDeferredValue z useMemo i useCallback. Filtrowanie i sortowanie zależą tylko od opóźnionych wartości:
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')}>Nazwa</th>
<th onClick={() => handleSort('category')}>Kategoria</th>
<th onClick={() => handleSort('price')}>Cena</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>
);
}Sortujemy kopię [...filtered], bo sort zmienia tablicę w miejscu i bez kopii psułby memoizowane data. Porównanie przez String z opcją numeric obsługuje też kolumnę z ceną, która jest liczbą.
3. Czego unikać
Ostatni przykład pokazuje nadmiar dobrych chęci. Trzy osobne opóźnienia dla prostego formularza tylko komplikują kod:
// ŹLE - Nadmierne użycie
function OverusedDeferred() {
const [name, setName] = useState('');
const [age, setAge] = useState(0);
const [email, setEmail] = useState('');
// Nie każda wartość potrzebuje deferred!
const deferredName = useDeferredValue(name);
const deferredAge = useDeferredValue(age);
const deferredEmail = useDeferredValue(email);
return <SimpleForm name={deferredName} age={deferredAge} email={deferredEmail} />;
}
// LEPIEJ - Selektywne użycie
function BetterApproach() {
const [formData, setFormData] = useState({ name: '', age: 0, email: '' });
const deferredFormData = useDeferredValue(formData);
return <HeavyValidationForm data={deferredFormData} />;
}Lepiej opóźnić jeden obiekt przekazywany do naprawdę ciężkiego komponentu.
useDeferredValue to elegancki sposób na poprawę wydajności aplikacji React bez skomplikowanego zarządzania stanem. Pozwala na zachowanie responsywności krytycznych elementów UI podczas wykonywania ciężkich operacji w tle.
Mierz, zanim zoptymalizujesz: wirtualizację długich list poznasz w kolejnej lekcji. Pamiętaj: opóźniona wartość to echo radaru, które mapa galaktyki odczyta, gdy tylko pilot skończy manewr.
Kod do tej lekcji: App.jsx
import { useDeferredValue, useState, memo, useMemo } from 'react';
// Symulacja ciężkiej operacji - renderowanie wielu elementów
function generateItems(count, filter = '') {
const items = [];
for (let i = 0; i < count; i++) {
const name = `Produkt ${i + 1}`;
const category = ['Elektronika', 'Książki', 'Odzież', 'Dom', 'Sport'][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;
}
// Komponent zoptymalizowany z memo
const ProductList = memo(function ProductList({ items, isStale }) {
// Symulacja ciężkich obliczeń
const processedItems = useMemo(() => {
return items.map(item => ({
...item,
displayPrice: `${item.price} zł`,
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'
}}>
Aktualizowanie wyników...
</div>
)}
{processedItems.length === 0 ? (
<div style={{
padding: '40px',
textAlign: 'center',
color: '#666'
}}>
Brak produktów spełniających kryteria
</div>
) : (
<div style={{ padding: '16px' }}>
<div style={{
marginBottom: '16px',
fontSize: '14px',
color: '#666',
borderBottom: '1px solid #eee',
paddingBottom: '8px'
}}>
Znaleziono {processedItems.length} produktów
</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 ? 'Na stanie' : 'Brak w magazynie'}
</div>
</div>
))}
</div>
</div>
)}
</div>
);
});
function DeferredValueDemo() {
const [query, setQuery] = useState('');
const [category, setCategory] = useState('');
const [sortBy, setSortBy] = useState('name');
// DEFERRED VALUES - będą się aktualizować z opóźnieniem
const deferredQuery = useDeferredValue(query);
const deferredCategory = useDeferredValue(category);
const deferredSortBy = useDeferredValue(sortBy);
// Sprawdzamy czy wartości są "stare" (nieaktualne)
const isStale = deferredQuery !== query ||
deferredCategory !== category ||
deferredSortBy !== sortBy;
// Generowanie wyników na podstawie DEFERRED wartości
const results = useMemo(() => {
let items = generateItems(8000, deferredQuery);
// Filtrowanie po kategorii
if (deferredCategory) {
items = items.filter(item =>
item.category.toLowerCase().includes(deferredCategory.toLowerCase())
);
}
// Sortowanie
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 - Sklep Online</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'
}}>
Wyszukaj produkt:
</label>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Wpisz nazwę produktu..."
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'
}}>
Kategoria:
</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="">Wszystkie kategorie</option>
<option value="Elektronika">Elektronika</option>
<option value="Książki">Książki</option>
<option value="Odzież">Odzież</option>
<option value="Dom">Dom</option>
<option value="Sport">Sport</option>
</select>
</div>
<div style={{ flex: '1', minWidth: '150px' }}>
<label style={{
display: 'block',
marginBottom: '4px',
fontSize: '14px',
fontWeight: 'bold'
}}>
Sortuj według:
</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">Nazwa</option>
<option value="price">Cena</option>
<option value="rating">Ocena</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>Status filtrów:</strong>
<ul style={{ margin: '4px 0', paddingLeft: '20px' }}>
<li>Wyszukiwanie: "{query}" {deferredQuery !== query && '(aktualizowanie...)'}</li>
<li>Kategoria: {category || 'Wszystkie'} {deferredCategory !== category && '(aktualizowanie...)'}</li>
<li>Sortowanie: {sortBy} {deferredSortBy !== sortBy && '(aktualizowanie...)'}</li>
</ul>
</div>
<div style={{ textAlign: 'right' }}>
{isStale ? (
<span style={{ color: '#ff9800', fontWeight: 'bold' }}>
Aktualizowanie wyników...
</span>
) : (
<span style={{ color: '#4caf50', fontWeight: 'bold' }}>
Wyniki aktualne
</span>
)}
</div>
</div>
<ProductList items={results} isStale={isStale} />
<div style={{
marginTop: '20px',
padding: '16px',
backgroundColor: '#f1f8e9',
borderRadius: '8px',
fontSize: '14px'
}}>
<strong>Co obserwować w tym demo:</strong>
<ul style={{ margin: '10px 0', paddingLeft: '20px' }}>
<li><strong>Responsywne inputy:</strong> Wszystkie kontrolki reagują natychmiast</li>
<li><strong>Odroczone renderowanie:</strong> Lista produktów aktualizuje się z opóźnieniem</li>
<li><strong>Wskaźnik "stale":</strong> Widoczny gdy dane są nieaktualne</li>
<li><strong>Przezroczystość:</strong> Lista staje się przezroczysta podczas aktualizacji</li>
<li><strong>Optymalizacja memo:</strong> Komponent się nie re-renderuje gdy props są identyczne</li>
</ul>
<div style={{
marginTop: '12px',
padding: '8px',
backgroundColor: '#fff3e0',
borderRadius: '4px'
}}>
<strong>Spróbuj:</strong> Szybko zmieniaj filtry i zobacz jak React priorytetyzuje
responsywność inputów nad renderowaniem listy produktów!
</div>
</div>
</div>
);
}
function ComparisonDemo() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
// Symulacja różnych sposobów obsługi
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>Porównanie: useDeferredValue vs bez optymalizacji</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'
}}
>
Z useDeferredValue
</button>
<button
onClick={() => setVersion('immediate')}
style={{
padding: '10px 20px',
backgroundColor: version === 'immediate' ? '#dc3545' : '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Bez optymalizacji
</button>
</div>
<div style={{ marginBottom: '20px' }}>
<label style={{
display: 'block',
marginBottom: '8px',
fontSize: '16px',
fontWeight: 'bold'
}}>
Wyszukaj produkty:
</label>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Spróbuj szybko pisać i zobacz różnicę..."
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>Aktualna wartość: "{query}"</span>
<span>
{version === 'deferred' && deferredQuery !== query && (
<span style={{ color: '#ff9800' }}>
Renderowanie: "{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'
}}>
Brak wyników
</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} zł
</div>
</div>
))
)}
</div>
<div style={{
marginTop: '16px',
padding: '12px',
backgroundColor: version === 'deferred' ? '#d4edda' : '#f8d7da',
borderRadius: '8px',
fontSize: '14px'
}}>
<strong>
{version === 'deferred' ? 'Z useDeferredValue:' : 'Bez optymalizacji:'}
</strong>
<p style={{ margin: '8px 0' }}>
{version === 'deferred'
? 'Input pozostaje responsywny, lista aktualizuje się z opóźnieniem przy szybkim pisaniu.'
: 'Każda zmiana w input natychmiast renderuje całą listę, co może powodować lagowanie.'
}
</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'
}}
>
Sklep Online
</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'
}}
>
Porównanie
</button>
</div>
</nav>
{activeDemo === 'shop' ? <DeferredValueDemo /> : <ComparisonDemo />}
</div>
);
}Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Zadania praktyczne w grze
- Układanie w poziomie
Ułóż składnię hooka useDeferredValue:
- Układanie w poziomie
Ułóż składnię destrukturyzacji hooka useTransition: