Kurs JavaScript i React · Moduł 9: Nowoczesne hooki React
use - uniwersalny hook do obsługi Promise i Context
W tej lekcji6
Stacja orbitalna czeka na raport z sondy. Do tej pory w React oznaczało to trzy stany (loading, error, data), efekt z fetch i sporo warunków w JSX. Do tego zwykłe hooki nie mogą stać w if, więc kontekst odczytywałeś nawet wtedy, gdy go nie potrzebowałeś.
use to API React, które pozwala na "używanie" zasobów takich jak Promise czy Context. W React 19 jest stabilne (wcześniej było dostępne tylko w wersjach eksperymentalnych). Jest to pierwszy hook, który może być wywoływany warunkowo i w pętlach. Nadal jednak musi być wywołany wewnątrz komponentu lub hooka, a według react.dev nie wolno go umieszczać w bloku try/catch.
Podstawy use
1. Czytanie Promise z use
Gdy przekażesz do use obiekt Promise, komponent "zawiesza się", a najbliższa granica Suspense pokazuje fallback do czasu rozwiązania obietnicy:
import { use, Suspense } from 'react';
// Funkcja zwracająca Promise
function fetchUser(id) {
return fetch(`/api/users/${id}`).then(res => res.json());
}
// Komponent używający use z Promise
function UserProfile({ userPromise }) {
// use automatycznie "rozpakowuje" Promise
const user = use(userPromise);
return (
<div style={{
padding: '20px',
border: '1px solid #ddd',
borderRadius: '8px'
}}>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Dołączył: {new Date(user.joinedDate).toLocaleDateString('pl-PL')}</p>
</div>
);
}
// Komponent rodzic
function UserDashboard({ userId }) {
// Uwaga: nowy Promise powstaje przy KAŻDYM renderze rodzica (rozwiązanie: cache, niżej)
const userPromise = fetchUser(userId);
return (
<div>
<h1>Panel użytkownika</h1>
<Suspense fallback={<div>Ładowanie danych użytkownika...</div>}>
<UserProfile userPromise={userPromise} />
</Suspense>
</div>
);
}UserProfile czyta dane jak zwykłą wartość, bez stanu ładowania. Problem tkwi w rodzicu: fetchUser(userId) tworzy nowy Promise przy każdym renderze UserDashboard, więc każde przerysowanie wysyła nowe zapytanie. React zaleca Promise pochodzące z Server Component, z frameworka albo z cache. Takie cache zbudujemy w sekcji zaawansowanej.
2. Używanie use z Context
use odczytuje też kontekst, tak jak useContext, ale może stać w warunku. Zobacz trzy komponenty korzystające z dwóch kontekstów:
import { use, createContext, useState } from 'react';
// Tworzenie Context
const ThemeContext = createContext(null);
const UserContext = createContext(null);
// Komponent używający use z Context
function Header() {
// use może być używany warunkowo!
const theme = use(ThemeContext);
const user = use(UserContext);
return (
<header style={{
backgroundColor: theme === 'dark' ? '#333' : '#f8f9fa',
color: theme === 'dark' ? '#fff' : '#333',
padding: '20px'
}}>
<h1>Witaj, {user.name}!</h1>
<p>Aktualny motyw: {theme}</p>
</header>
);
}
// Możliwość warunkowego użycia
function ConditionalComponent({ showUserInfo }) {
const theme = use(ThemeContext);
// use może być używany warunkowo - to niemożliwe z innymi hooks!
if (showUserInfo) {
const user = use(UserContext);
return <div>Użytkownik: {user.name}</div>;
}
return <div>Motyw: {theme}</div>;
}
// App z providers
function App() {
const [theme, setTheme] = useState('light');
const [user] = useState({ name: 'Jan Kowalski', id: 1 });
return (
<ThemeContext.Provider value={theme}>
<UserContext.Provider value={user}>
<div>
<Header />
<ConditionalComponent showUserInfo={true} />
<button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
Zmień motyw
</button>
</div>
</UserContext.Provider>
</ThemeContext.Provider>
);
}ConditionalComponent sięga po UserContext tylko wtedy, gdy ma pokazać użytkownika. Dostawców zapisaliśmy jako ThemeContext.Provider, co nadal działa, ale od React 19 wystarczy krótszy zapis <ThemeContext value={theme}>, a Provider ma zostać w przyszłości wycofany.
3. use w pętlach
Hook może też wystąpić w pętli, co jest nie do pomyślenia przy useState. Kluczowe jest, by każdy Promise pochodził z cache:
import { use, Suspense } from 'react';
// Funkcja tworząca Promise dla każdego posta
const postCache = new Map();
function fetchPost(id) {
if (!postCache.has(id)) {
postCache.set(id, fetch(`/api/posts/${id}`).then(res => res.json()));
}
return postCache.get(id);
}
// Komponent wyświetlający wiele postów
function PostList({ postIds }) {
const posts = [];
for (const id of postIds) {
// use może być wywołany w pętli!
posts.push(use(fetchPost(id)));
}
return (
<div>
{posts.map(post => (
<article
key={post.id}
style={{
marginBottom: '20px',
padding: '15px',
backgroundColor: '#f8f9fa',
borderRadius: '8px'
}}
>
<h3>{post.title}</h3>
<p>{post.content}</p>
<small>Autor: {post.author}</small>
</article>
))}
</div>
);
}
// Wrapper z Suspense
function BlogSection() {
const postIds = [1, 2, 3, 4, 5];
return (
<section>
<h2>Najnowsze posty</h2>
<Suspense fallback={<PostListSkeleton count={5} />}>
<PostList postIds={postIds} />
</Suspense>
</section>
);
}
function PostListSkeleton({ count }) {
return (
<div>
{Array.from({ length: count }).map((_, i) => (
<div
key={i}
style={{
marginBottom: '20px',
padding: '15px',
backgroundColor: '#e9ecef',
borderRadius: '8px',
height: '100px'
}}
/>
))}
</div>
);
}Pętla for...of stoi wprost w ciele komponentu. Gdyby use siedział w callbacku przekazanym do map, wywołałaby go zwykła funkcja, a nie komponent, i linter Reacta zgłosiłby błąd. Funkcja fetchPost trzyma obietnice w postCache. Bez tego każda ponowna próba renderu po zawieszeniu tworzyłaby nowe obietnice i lista nigdy by się nie załadowała.
Zaawansowane wzorce z use
1. Cache dla Promise
Uogólnijmy ten pomysł. getCachedPromise przyjmuje klucz i fabrykę, a Promise powstaje tylko przy pierwszym zapytaniu o dany klucz:
import { use, Suspense, useState } from 'react';
// Prosty cache dla Promise
const promiseCache = new Map();
function getCachedPromise(key, promiseFactory) {
if (!promiseCache.has(key)) {
promiseCache.set(key, promiseFactory());
}
return promiseCache.get(key);
}
// API functions
function fetchUserData(userId) {
const cached = getCachedPromise(
`user-${userId}`,
() => fetch(`/api/users/${userId}`).then(res => res.json())
);
return cached;
}
function fetchUserPosts(userId) {
const cached = getCachedPromise(
`posts-${userId}`,
() => fetch(`/api/users/${userId}/posts`).then(res => res.json())
);
return cached;
}
// Komponenty
function UserInfo({ userId }) {
const userPromise = fetchUserData(userId);
const user = use(userPromise);
return (
<div style={{
padding: '20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px',
marginBottom: '20px'
}}>
<h2>{user.name}</h2>
<p>{user.email}</p>
<p>{user.location}</p>
<p>Dołączył: {new Date(user.joinedDate).toLocaleDateString('pl-PL')}</p>
</div>
);
}
function UserPosts({ userId }) {
const postsPromise = fetchUserPosts(userId);
const posts = use(postsPromise);
return (
<div>
<h3>Posty użytkownika ({posts.length})</h3>
{posts.map(post => (
<article
key={post.id}
style={{
marginBottom: '15px',
padding: '15px',
border: '1px solid #e9ecef',
borderRadius: '6px'
}}
>
<h4>{post.title}</h4>
<p>{post.excerpt}</p>
<small>{new Date(post.date).toLocaleDateString('pl-PL')}</small>
</article>
))}
</div>
);
}
function UserProfilePage() {
const [userId, setUserId] = useState(1);
return (
<div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
<div style={{ marginBottom: '20px' }}>
<button onClick={() => setUserId(1)} disabled={userId === 1}>
Użytkownik 1
</button>
<button onClick={() => setUserId(2)} disabled={userId === 2}>
Użytkownik 2
</button>
<button onClick={() => promiseCache.clear()}>
Wyczyść cache
</button>
</div>
<Suspense fallback={<div>Ładowanie profilu...</div>}>
<UserInfo userId={userId} />
</Suspense>
<Suspense fallback={<div>Ładowanie postów...</div>}>
<UserPosts userId={userId} />
</Suspense>
</div>
);
}Dwie osobne granice Suspense sprawiają, że profil i posty pojawiają się niezależnie. Przycisk "Wyczyść cache" usuwa obietnice, ale nie wymusza nowego renderu, więc nowe dane pobiorą się przy następnej zmianie użytkownika.
2. Równoległe ładowanie danych
Promise.all pobiera kilka zasobów jednocześnie, a use czeka na wszystkie naraz. Najpierw funkcja API i komponent dashboardu:
import { use, Suspense } from 'react';
// Funkcje API
async function fetchDashboardData() {
const [stats, activities, notifications] = await Promise.all([
fetch('/api/stats').then(res => res.json()),
fetch('/api/activities').then(res => res.json()),
fetch('/api/notifications').then(res => res.json())
]);
return { stats, activities, notifications };
}
// Komponent dashboardu
function Dashboard({ dataPromise }) {
const { stats, activities, notifications } = use(dataPromise);
return (
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
gap: '20px',
padding: '20px'
}}>
<StatsCard stats={stats} />
<ActivitiesCard activities={activities} />
<NotificationsCard notifications={notifications} />
</div>
);
}
Dane trafiają do trzech kart przez propsy, więc karty są zwykłymi komponentami. Oto ich implementacja:
function StatsCard({ stats }) {
return (
<div style={{
padding: '20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
}}>
<h3>Statystyki</h3>
<div style={{ display: 'grid', gap: '10px' }}>
<div>
<strong>Użytkownicy:</strong> {stats.users.toLocaleString('pl-PL')}
</div>
<div>
<strong>Przychód:</strong> {stats.revenue.toLocaleString('pl-PL', {
style: 'currency',
currency: 'PLN'
})}
</div>
<div>
<strong>Wzrost:</strong>
<span style={{ color: stats.growth > 0 ? '#28a745' : '#dc3545' }}>
{stats.growth > 0 ? '+' : ''}{stats.growth}%
</span>
</div>
</div>
</div>
);
}
function ActivitiesCard({ activities }) {
return (
<div style={{
padding: '20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
}}>
<h3>Ostatnie aktywności</h3>
<ul style={{ listStyle: 'none', padding: 0 }}>
{activities.slice(0, 5).map(activity => (
<li
key={activity.id}
style={{
padding: '8px 0',
borderBottom: '1px solid #e9ecef'
}}
>
<div style={{ fontWeight: '500' }}>{activity.user}</div>
<div style={{ fontSize: '14px', color: '#6c757d' }}>
{activity.action}
</div>
<small style={{ color: '#6c757d' }}>
{new Date(activity.timestamp).toLocaleString('pl-PL')}
</small>
</li>
))}
</ul>
</div>
);
}
function NotificationsCard({ notifications }) {
const unreadCount = notifications.filter(n => !n.read).length;
return (
<div style={{
padding: '20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
}}>
<h3>
Powiadomienia
{unreadCount > 0 && (
<span style={{
marginLeft: '10px',
padding: '2px 8px',
backgroundColor: '#dc3545',
color: 'white',
borderRadius: '12px',
fontSize: '14px'
}}>
{unreadCount}
</span>
)}
</h3>
<div style={{ maxHeight: '200px', overflowY: 'auto' }}>
{notifications.map(notification => (
<div
key={notification.id}
style={{
padding: '10px',
marginBottom: '8px',
backgroundColor: notification.read ? 'transparent' : '#e3f2fd',
borderRadius: '4px',
fontSize: '14px'
}}
>
<strong>{notification.title}</strong>
<p style={{ margin: '4px 0' }}>{notification.message}</p>
</div>
))}
</div>
</div>
);
}
Żadna karta nie wie o Promise ani o Suspense. Na koniec komponent główny i szkielet:
// Główny komponent
function DashboardApp() {
const dataPromise = fetchDashboardData();
return (
<div>
<h1 style={{ padding: '20px' }}>Panel administracyjny</h1>
<Suspense fallback={<DashboardSkeleton />}>
<Dashboard dataPromise={dataPromise} />
</Suspense>
</div>
);
}
function DashboardSkeleton() {
return (
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
gap: '20px',
padding: '20px'
}}>
{[1, 2, 3].map(i => (
<div
key={i}
style={{
height: '250px',
backgroundColor: '#e9ecef',
borderRadius: '8px',
animation: 'pulse 1.5s ease-in-out infinite'
}}
/>
))}
</div>
);
}Tu znów Promise powstaje w renderze DashboardApp, więc w prawdziwej aplikacji przenieś go do cache albo do Server Component.
3. Error boundaries z use
Odrzucony Promise nie trafia do try/catch, tylko do najbliższego Error Boundary. Najpierw sama granica błędów, która wciąż wymaga komponentu klasowego:
import { use, Suspense, Component, useState } from 'react';
// Error Boundary
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught by boundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return (
<div style={{
padding: '20px',
backgroundColor: '#f8d7da',
border: '1px solid #f5c6cb',
borderRadius: '8px',
color: '#721c24'
}}>
<h3>Coś poszło nie tak</h3>
<p>{this.state.error?.message || 'Nieznany błąd'}</p>
<button
onClick={() => this.setState({ hasError: false, error: null })}
style={{
marginTop: '10px',
padding: '8px 16px',
backgroundColor: '#721c24',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Spróbuj ponownie
</button>
</div>
);
}
return this.props.children;
}
}
getDerivedStateFromError przełącza widok na komunikat, a componentDidCatch loguje błąd. Teraz demo, które potrafi symulować awarię:
// Funkcja API która może zwrócić błąd
function fetchDataWithError(shouldFail = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) {
reject(new Error('Błąd pobierania danych z serwera'));
} else {
resolve({
message: 'Dane załadowane pomyślnie!',
timestamp: new Date().toISOString()
});
}
}, 1000);
});
}
// Komponent używający use
function DataDisplay({ dataPromise }) {
const data = use(dataPromise);
return (
<div style={{
padding: '20px',
backgroundColor: '#d4edda',
border: '1px solid #c3e6cb',
borderRadius: '8px',
color: '#155724'
}}>
<h3>Sukces!</h3>
<p>{data.message}</p>
<small>Załadowano: {new Date(data.timestamp).toLocaleString('pl-PL')}</small>
</div>
);
}
// Główny komponent
function ErrorHandlingDemo() {
const [shouldFail, setShouldFail] = useState(false);
const [key, setKey] = useState(0);
const dataPromise = fetchDataWithError(shouldFail);
return (
<div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
<h2>Obsługa błędów z use</h2>
<div style={{ marginBottom: '20px' }}>
<label>
<input
type="checkbox"
checked={shouldFail}
onChange={(e) => setShouldFail(e.target.checked)}
/>
Symuluj błąd
</label>
<button
onClick={() => setKey(k => k + 1)}
style={{ marginLeft: '20px' }}
>
Odśwież
</button>
</div>
<ErrorBoundary key={key}>
<Suspense fallback={
<div style={{
padding: '20px',
backgroundColor: '#cfe2ff',
border: '1px solid #b6d4fe',
borderRadius: '8px',
color: '#084298'
}}>
Ładowanie danych...
</div>
}>
<DataDisplay dataPromise={dataPromise} />
</Suspense>
</ErrorBoundary>
</div>
);
}Zmiana key na ErrorBoundary tworzy granicę od nowa, co resetuje błąd. Zamiast granicy możesz też dopisać do obietnicy .catch(), zwracający wartość zastępczą.
Praktyczne zastosowania use
1. System routingu z lazy loading
Prosty router łączy lazy, Suspense i kontekst odczytywany przez use:
import { use, Suspense, lazy, useState, createContext } from 'react';
// Symulacja systemu routingu
const routes = {
'/': lazy(() => import('./pages/Home')),
'/about': lazy(() => import('./pages/About')),
'/contact': lazy(() => import('./pages/Contact')),
'/profile': lazy(() => import('./pages/Profile'))
};
// Context dla routingu
const RouteContext = createContext(null);
// Hook do nawigacji
function useNavigation() {
const { navigate } = use(RouteContext);
return navigate;
}
// Komponent strony
function Page({ path }) {
const Component = routes[path] || routes['/'];
return (
<Suspense fallback={<PageLoader />}>
<Component />
</Suspense>
);
}
function PageLoader() {
return (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: '400px'
}}>
<div style={{ textAlign: 'center' }}>
<div style={{
width: '50px',
height: '50px',
border: '3px solid #f3f3f3',
borderTop: '3px solid #007bff',
borderRadius: '50%',
animation: 'spin 1s linear infinite',
margin: '0 auto 20px'
}} />
<p>Ładowanie strony...</p>
</div>
</div>
);
}
// Główna aplikacja
function RouterApp() {
const [currentPath, setCurrentPath] = useState('/');
const navigate = (path) => {
setCurrentPath(path);
window.history.pushState({}, '', path);
};
return (
<RouteContext.Provider value={{ navigate, currentPath }}>
<div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
<Navigation />
<main style={{ flex: 1, padding: '20px' }}>
<Page path={currentPath} />
</main>
</div>
</RouteContext.Provider>
);
}
function Navigation() {
const navigate = useNavigation();
const { currentPath } = use(RouteContext);
const links = [
{ path: '/', label: 'Strona główna' },
{ path: '/about', label: 'O nas' },
{ path: '/contact', label: 'Kontakt' },
{ path: '/profile', label: 'Profil' }
];
return (
<nav style={{
backgroundColor: '#333',
padding: '10px 20px'
}}>
{links.map(link => (
<button
key={link.path}
onClick={() => navigate(link.path)}
style={{
marginRight: '10px',
padding: '8px 16px',
backgroundColor: currentPath === link.path ? '#007bff' : 'transparent',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
{link.label}
</button>
))}
</nav>
);
}lazy ładuje kod strony dopiero przy pierwszym wejściu, a Suspense pokazuje PageLoader. To tylko model, bo w praktyce użyjesz React Router lub routera frameworka.
2. Dynamiczne formularze z walidacją
Formularz trzyma stan w kontekście, a pola odczytują go przez use. Najpierw kontekst, hook pola i komponent FormField:
import { use, createContext, useState } from 'react';
// Context dla formularza
const FormContext = createContext(null);
// Hook do zarządzania formularzem
function useFormField(name) {
const form = use(FormContext);
return {
value: form.values[name] || '',
error: form.errors[name],
onChange: (e) => form.setValue(name, e.target.value),
onBlur: () => form.validateField(name)
};
}
// Komponent pola formularza
function FormField({ name, label, type = 'text', validate }) {
const field = useFormField(name);
const form = use(FormContext);
// Rejestracja walidatora
if (validate && !form.validators[name]) {
form.registerValidator(name, validate);
}
return (
<div style={{ marginBottom: '15px' }}>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
{label}
</label>
<input
type={type}
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
style={{
width: '100%',
padding: '8px',
border: `1px solid ${field.error ? '#dc3545' : '#ddd'}`,
borderRadius: '4px'
}}
/>
{field.error && (
<div style={{ color: '#dc3545', fontSize: '14px', marginTop: '5px' }}>
{field.error}
</div>
)}
</div>
);
}
Każde pole rejestruje swój walidator i pokazuje własny błąd. Teraz dostawca, który trzyma wartości i uruchamia walidację:
// Provider formularza
function FormProvider({ children, onSubmit }) {
const [values, setValues] = useState({});
const [errors, setErrors] = useState({});
const [validators] = useState({});
const setValue = (name, value) => {
setValues(prev => ({ ...prev, [name]: value }));
// Czyść błąd przy zmianie wartości
setErrors(prev => ({ ...prev, [name]: '' }));
};
const registerValidator = (name, validate) => {
validators[name] = validate;
};
const validateField = (name) => {
if (validators[name]) {
const error = validators[name](values[name], values);
setErrors(prev => ({ ...prev, [name]: error }));
return !error;
}
return true;
};
const validateAll = () => {
const newErrors = {};
let isValid = true;
Object.keys(validators).forEach(name => {
const error = validators[name](values[name], values);
if (error) {
newErrors[name] = error;
isValid = false;
}
});
setErrors(newErrors);
return isValid;
};
const handleSubmit = (e) => {
e.preventDefault();
if (validateAll()) {
onSubmit(values);
}
};
const formValue = {
values,
errors,
validators,
setValue,
registerValidator,
validateField,
handleSubmit
};
return (
<FormContext.Provider value={formValue}>
<form onSubmit={handleSubmit}>
{children}
</form>
</FormContext.Provider>
);
}
Walidatory dostają drugi argument, czyli wszystkie wartości formularza. To ważne w przykładzie użycia:
// Przykład użycia
function RegistrationFormExample() {
const handleSubmit = (values) => {
console.log('Form submitted:', values);
alert('Rejestracja zakończona sukcesem!');
};
return (
<div style={{ maxWidth: '400px', margin: '0 auto', padding: '20px' }}>
<h2>Formularz rejestracji</h2>
<FormProvider onSubmit={handleSubmit}>
<FormField
name="email"
label="Email"
type="email"
validate={(value) => {
if (!value) return 'Email jest wymagany';
if (!/\S+@\S+\.\S+/.test(value)) return 'Nieprawidłowy email';
return '';
}}
/>
<FormField
name="password"
label="Hasło"
type="password"
validate={(value) => {
if (!value) return 'Hasło jest wymagane';
if (value.length < 8) return 'Hasło musi mieć minimum 8 znaków';
return '';
}}
/>
<FormField
name="confirmPassword"
label="Potwierdź hasło"
type="password"
validate={(value, allValues) => {
if (value !== allValues.password) return 'Hasła nie są identyczne';
return '';
}}
/>
<button
type="submit"
style={{
width: '100%',
padding: '10px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
fontSize: '16px',
cursor: 'pointer'
}}
>
Zarejestruj się
</button>
</FormProvider>
</div>
);
}Pole "Potwierdź hasło" porównuje wartość z allValues.password. Nie może zawołać use w walidatorze, bo use działa tylko podczas renderu komponentu lub hooka, a walidator uruchamia się w obsłudze zdarzenia.
Najlepsze praktyki z use
1. Kiedy używać use
Oto dobre i złe zastosowania w pigułce:
// DOBRZE - warunkowe użycie
function ConditionalData({ showDetails }) {
if (showDetails) {
const details = use(detailsPromise);
return <DetailView details={details} />;
}
return <Summary />;
}
// DOBRZE - w pętlach
function MultipleResources({ resourceIds }) {
const resources = [];
for (const id of resourceIds) {
resources.push(use(fetchResource(id)));
}
return <ResourceList resources={resources} />;
}
// ŹLE - niepotrzebne użycie dla prostych wartości
function BadExample() {
const value = use(Promise.resolve(42)); // Niepotrzebne!
return <div>{value}</div>;
}W MultipleResources funkcja fetchResource musi zwracać Promise z cache, tak jak fetchPost wyżej.
2. Cache i optymalizacja
Cache można zamknąć we własnym hooku:
// Implementacja prostego cache
const cache = new Map();
function useCachedResource(key, fetcher) {
if (!cache.has(key)) {
cache.set(key, fetcher());
}
const promise = cache.get(key);
const resource = use(promise);
return resource;
}
// Użycie
function CachedDataComponent({ userId }) {
const userData = useCachedResource(
`user-${userId}`,
() => fetchUser(userId)
);
return <UserProfile user={userData} />;
}useCachedResource to zwykły custom hook, a Map na poziomie modułu przetrwa między renderami.
3. Obsługa błędów
Ponawianie z wykładniczym odstępem da się zamknąć w fabryce obietnic:
// Wrapper z retry logic
function createRetryablePromise(fetcher, maxRetries = 3) {
return async () => {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
return await fetcher();
} catch (error) {
lastError = error;
if (i < maxRetries - 1) {
// Exponential backoff
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, i) * 1000)
);
}
}
}
throw lastError;
};
}
// Użycie
function RobustDataFetching() {
const dataPromise = createRetryablePromise(
() => fetch('/api/critical-data').then(res => res.json())
)();
return (
<ErrorBoundary>
<Suspense fallback={<div>Ładowanie...</div>}>
<DataComponent dataPromise={dataPromise} />
</Suspense>
</ErrorBoundary>
);
}Tu także Promise powstaje w renderze, więc w produkcji połącz go z cache.
Powtórka przed zadaniami: memo z własnym porównaniem i proces optymalizacji
Zadania po tej lekcji wracają do memo. Domyślnie memo porównuje każdy props płytko, przez Object.is. Drugim argumentem możesz podać własną funkcję arePropsEqual(prevProps, nextProps): gdy zwróci true, React uzna propsy za równe i pominie render, a gdy zwróci false, wyrenderuje komponent:
import { memo } from 'react';
const TelemetryPanel = memo(function TelemetryPanel({ readings, title }) {
return <Chart data={readings} label={title} />;
}, (prevProps, nextProps) =>
// true = propsy uznajemy za równe, więc React pominie render
prevProps.readings.length === nextProps.readings.length && prevProps.title === nextProps.title
);Funkcja nie robi niczego sama z siebie, na przykład nie włącza głębokiego porównania obiektów: liczy się tylko to, co w niej napiszesz. Pomyłka w porównaniu oznacza nieaktualny ekran, dlatego sięgaj po nią rzadko.
Każda z tych technik to narzędzie, a nie cel. Optymalizację prowadź zawsze w tej samej kolejności: najpierw pomiar początkowy (baseline), potem profilowanie, które pokaże, gdzie ucieka czas renderu, następnie identyfikacja wąskiego gardła i implementacja jednej poprawki. Na końcu mierzysz wpływ zmiany i uruchamiasz testy regresji, żeby sprawdzić, czy aplikacja działa tak jak wcześniej. Te dwa ostatnie kroki możesz zrobić w dowolnej kolejności, byle żadnego nie pominąć.
Podsumowanie
Hook use otwiera nowe możliwości w React, pozwalając na bardziej elastyczne zarządzanie asynchronicznymi danymi i kontekstem. Jego unikalna zdolność do używania warunkowego i w pętlach czyni go potężnym narzędziem dla zaawansowanych aplikacji.
Moja rada: nie twórz Promise w komponencie klienckim bez cache. Pamiętaj: use to odbiornik stacji, który czeka na raport sondy, ale sam raport musi mieć jeden stały kanał.
Kod do tej lekcji: App.jsx
import React, { use, createContext, useState, Suspense } from 'react';
// Konteksty aplikacji kosmicznej
const ThemeContext = createContext('dark');
const CrewContext = createContext(null);
// Symulacja pobierania danych z API (Promise)
function fetchMissionData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: 'Misja Andromeda',
status: 'W trakcie',
crew: 7,
distance: '2.537 mln ly',
fuelLevel: 78,
});
}, 1500);
});
}
// Komponent odczytujący dane z Context za pomocą use()
function CrewPanel() {
// use() z Context - działa jak useContext, ale może być warunkowe!
const crew = use(CrewContext);
const theme = use(ThemeContext);
const isDark = theme === 'dark';
return (
<div style={{
padding: '16px', marginBottom: '16px',
background: isDark ? 'rgba(0, 212, 255, 0.08)' : '#f0f8ff',
borderRadius: '10px', border: `1px solid ${isDark ? '#1a3a5c' : '#b0d4f1'}`,
}}>
<h3 style={{ color: isDark ? '#00d4ff' : '#0066cc', margin: '0 0 8px' }}>
Załoga statku
</h3>
{crew.map((member) => (
<div key={member.id} style={{
display: 'flex', justifyContent: 'space-between',
padding: '6px 0', borderBottom: `1px solid ${isDark ? '#1a2a3c' : '#dde8f0'}`,
color: isDark ? '#c0c8d0' : '#333', fontSize: '14px',
}}>
<span>{member.name}</span>
<span style={{ color: isDark ? '#778da9' : '#666' }}>{member.role}</span>
</div>
))}
</div>
);
}
// Komponent odczytujący Promise za pomocą use()
function MissionDetails({ missionPromise }) {
// use() automatycznie "rozpakowuje" Promise
const mission = use(missionPromise);
return (
<div style={{
padding: '20px', background: 'rgba(255, 215, 0, 0.08)',
borderRadius: '10px', border: '1px solid #3a3a1c',
}}>
<h3 style={{ color: '#ffd700', margin: '0 0 12px' }}>
{mission.name}
</h3>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
{[
['Status', mission.status],
['Załoga', `${mission.crew} osób`],
['Dystans', mission.distance],
['Paliwo', `${mission.fuelLevel}%`],
].map(([label, value]) => (
<div key={label} style={{
padding: '10px', background: 'rgba(255, 255, 255, 0.03)',
borderRadius: '6px', fontSize: '13px',
}}>
<div style={{ color: '#778da9', marginBottom: '4px' }}>{label}</div>
<div style={{ color: '#e0e1dd', fontWeight: 'bold' }}>{value}</div>
</div>
))}
</div>
</div>
);
}
// use() może stać w warunku: tu kontekst czytamy tylko wtedy, gdy szczegóły są widoczne.
// Z useContext takie wywołanie po instrukcji return byłoby niedozwolone.
function ConditionalInfo({ showDetails }) {
if (!showDetails) {
return (
<div style={{
padding: '12px', marginTop: '16px',
background: 'rgba(255, 255, 255, 0.03)',
borderRadius: '8px', color: '#778da9', fontSize: '13px',
}}>
Szczegóły ukryte
</div>
);
}
const crew = use(CrewContext);
return (
<div style={{
padding: '12px', marginTop: '16px',
background: 'rgba(0, 212, 255, 0.06)',
borderRadius: '8px', color: '#c0c8d0', fontSize: '13px',
}}>
Na pokładzie: {crew.length} członków załogi ({crew.map((member) => member.role).join(', ')})
</div>
);
}
function LoadingFallback() {
return (
<div style={{
padding: '40px', textAlign: 'center', color: '#778da9',
}}>
<div style={{ fontSize: '24px', marginBottom: '10px' }}>Ładowanie danych misji...</div>
<div style={{
width: '50px', height: '50px', margin: '0 auto',
border: '3px solid #1a3a5c', borderTop: '3px solid #00d4ff',
borderRadius: '50%', animation: 'spin 1s linear infinite',
}} />
</div>
);
}
export default function App() {
const [showDetails, setShowDetails] = useState(true);
const missionPromise = React.useMemo(() => fetchMissionData(), []);
const crewData = [
{ id: 1, name: 'Kapitan Nova', role: 'Dowódca' },
{ id: 2, name: 'Dr. Stella', role: 'Nawigator' },
{ id: 3, name: 'Inż. Orion', role: 'Mechanik' },
{ id: 4, name: 'Lt. Vega', role: 'Pilot' },
];
return (
<ThemeContext.Provider value="dark">
<CrewContext.Provider value={crewData}>
<div style={{
minHeight: '100vh',
background: 'linear-gradient(135deg, #0a0e27 0%, #1a1a3e 100%)',
padding: '24px', fontFamily: 'monospace',
}}>
<h1 style={{ color: '#00d4ff', textAlign: 'center', marginBottom: '8px' }}>
Hook use() - Promise i Context
</h1>
<p style={{ color: '#778da9', textAlign: 'center', marginBottom: '24px', fontSize: '14px' }}>
Nowy sposób na odczytywanie danych w React
</p>
<div style={{ maxWidth: '600px', margin: '0 auto' }}>
<CrewPanel />
<Suspense fallback={<LoadingFallback />}>
<MissionDetails missionPromise={missionPromise} />
</Suspense>
<div style={{ marginTop: '16px', textAlign: 'center' }}>
<button
onClick={() => setShowDetails(d => !d)}
style={{
padding: '10px 20px', background: '#1a3a5c',
border: 'none', borderRadius: '6px', color: '#00d4ff',
cursor: 'pointer', fontSize: '13px',
}}
>
{showDetails ? 'Ukryj szczegóły' : 'Pokaż szczegóły'}
</button>
</div>
<ConditionalInfo showDetails={showDetails} />
</div>
</div>
</CrewContext.Provider>
</ThemeContext.Provider>
);
}Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Jaki jest cel drugiego argumentu (custom comparator) w React.memo(Component, compareFn)?
Zadania praktyczne w grze
- Układanie w pionie
Uporządkuj workflow optymalizacji wydajności: