JavaScript and React course ยท Module 9: Modern React Hooks
use - universal hook for handling Promise and Context
In this lesson6
The orbital station is waiting for a report from a probe. Until now, in React that meant three states (loading, error, data), an effect with fetch and quite a few conditions in JSX. On top of that, regular hooks cannot sit inside an if, so you read context even when you did not need it.
use is a React API that allows you to "use" resources such as Promises or Context. In React 19 it is stable (earlier it was available only in experimental releases). It is the first hook that can be called conditionally and in loops. It still has to be called inside a component or a hook, though, and according to react.dev it must not be placed in a try/catch block.
use Basics
1. Reading Promise with use
When you pass a Promise to use, the component "suspends", and the nearest Suspense boundary shows a fallback until the promise resolves:
import { use, Suspense } from 'react';
// Function returning a Promise
function fetchUser(id) {
return fetch(`/api/users/${id}`).then(res => res.json());
}
// Component using use with Promise
function UserProfile({ userPromise }) {
// use automatically "unwraps" the 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>Joined: {new Date(user.joinedDate).toLocaleDateString('en-US')}</p>
</div>
);
}
// Parent component
function UserDashboard({ userId }) {
// Note: a new Promise is created on EVERY parent render (solution: a cache, below)
const userPromise = fetchUser(userId);
return (
<div>
<h1>User Dashboard</h1>
<Suspense fallback={<div>Loading user data...</div>}>
<UserProfile userPromise={userPromise} />
</Suspense>
</div>
);
}UserProfile reads the data like a plain value, with no loading state. The problem is in the parent: fetchUser(userId) creates a new Promise on every render of UserDashboard, so every redraw sends a new request. React recommends Promises that come from a Server Component, from a framework or from a cache. We will build such a cache in the advanced section.
2. Using use with Context
use also reads context, just like useContext, but it can sit inside a condition. Here are three components using two contexts:
import { use, createContext, useState } from 'react';
// Creating Context
const ThemeContext = createContext(null);
const UserContext = createContext(null);
// Component using use with Context
function Header() {
// use can be used conditionally!
const theme = use(ThemeContext);
const user = use(UserContext);
return (
<header style={{
backgroundColor: theme === 'dark' ? '#333' : '#f8f9fa',
color: theme === 'dark' ? '#fff' : '#333',
padding: '20px'
}}>
<h1>Welcome, {user.name}!</h1>
<p>Current theme: {theme}</p>
</header>
);
}
// Ability to use conditionally
function ConditionalComponent({ showUserInfo }) {
const theme = use(ThemeContext);
// use can be used conditionally - this is impossible with other hooks!
if (showUserInfo) {
const user = use(UserContext);
return <div>User: {user.name}</div>;
}
return <div>Theme: {theme}</div>;
}
// App with providers
function App() {
const [theme, setTheme] = useState('light');
const [user] = useState({ name: 'John Smith', id: 1 });
return (
<ThemeContext.Provider value={theme}>
<UserContext.Provider value={user}>
<div>
<Header />
<ConditionalComponent showUserInfo={true} />
<button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
</div>
</UserContext.Provider>
</ThemeContext.Provider>
);
}ConditionalComponent reaches for UserContext only when it has to show the user. We wrote the providers as ThemeContext.Provider, which still works, but since React 19 the shorter <ThemeContext value={theme}> is enough, and Provider is planned to be deprecated in the future.
3. use in loops
The hook can also appear in a loop, which is unthinkable with useState. The key is that every Promise comes from a cache:
import { use, Suspense } from 'react';
// Function creating a Promise for each post
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);
}
// Component displaying multiple posts
function PostList({ postIds }) {
const posts = [];
for (const id of postIds) {
// use can be called in a loop!
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>Author: {post.author}</small>
</article>
))}
</div>
);
}
// Wrapper with Suspense
function BlogSection() {
const postIds = [1, 2, 3, 4, 5];
return (
<section>
<h2>Latest Posts</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>
);
}The for...of loop sits directly in the component body. If use sat in a callback passed to map, a plain function would call it instead of the component, and the React linter would report an error. The fetchPost function keeps promises in postCache. Without it, every retry of the render after suspending would create new promises and the list would never load.
Advanced patterns with use
1. Cache for Promises
Let's generalize the idea. getCachedPromise takes a key and a factory, and the Promise is created only on the first request for a given key:
import { use, Suspense, useState } from 'react';
// Simple cache for Promises
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;
}
// Components
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>Joined: {new Date(user.joinedDate).toLocaleDateString('en-US')}</p>
</div>
);
}
function UserPosts({ userId }) {
const postsPromise = fetchUserPosts(userId);
const posts = use(postsPromise);
return (
<div>
<h3>User posts ({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('en-US')}</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}>
User 1
</button>
<button onClick={() => setUserId(2)} disabled={userId === 2}>
User 2
</button>
<button onClick={() => promiseCache.clear()}>
Clear cache
</button>
</div>
<Suspense fallback={<div>Loading profile...</div>}>
<UserInfo userId={userId} />
</Suspense>
<Suspense fallback={<div>Loading posts...</div>}>
<UserPosts userId={userId} />
</Suspense>
</div>
);
}Two separate Suspense boundaries let the profile and the posts appear independently. The "Clear cache" button removes the promises but does not force a new render, so fresh data will be fetched on the next user change.
2. Parallel data loading
Promise.all fetches several resources at once, and use waits for all of them together. First, the API function and the dashboard component:
import { use, Suspense } from 'react';
// API functions
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 };
}
// Dashboard component
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>
);
}
The data reaches the three cards through props, so the cards are ordinary components. Here is their implementation:
function StatsCard({ stats }) {
return (
<div style={{
padding: '20px',
backgroundColor: '#f8f9fa',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
}}>
<h3>Statistics</h3>
<div style={{ display: 'grid', gap: '10px' }}>
<div>
<strong>Users:</strong> {stats.users.toLocaleString('en-US')}
</div>
<div>
<strong>Revenue:</strong> {stats.revenue.toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
})}
</div>
<div>
<strong>Growth:</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>Recent Activities</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('en-US')}
</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>
Notifications
{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>
);
}
No card knows anything about Promises or Suspense. Finally, the main component and the skeleton:
// Main component
function DashboardApp() {
const dataPromise = fetchDashboardData();
return (
<div>
<h1 style={{ padding: '20px' }}>Admin Panel</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>
);
}Here again the Promise is created in the render of DashboardApp, so in a real application move it to a cache or a Server Component.
3. Error boundaries with use
A rejected Promise does not end up in a try/catch, but in the nearest Error Boundary. First the boundary itself, which still requires a class component:
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>Something went wrong</h3>
<p>{this.state.error?.message || 'Unknown error'}</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'
}}
>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
getDerivedStateFromError switches the view to a message, and componentDidCatch logs the error. Now a demo that can simulate a failure:
// API function that may return an error
function fetchDataWithError(shouldFail = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) {
reject(new Error('Error fetching data from server'));
} else {
resolve({
message: 'Data loaded successfully!',
timestamp: new Date().toISOString()
});
}
}, 1000);
});
}
// Component using use
function DataDisplay({ dataPromise }) {
const data = use(dataPromise);
return (
<div style={{
padding: '20px',
backgroundColor: '#d4edda',
border: '1px solid #c3e6cb',
borderRadius: '8px',
color: '#155724'
}}>
<h3>Success!</h3>
<p>{data.message}</p>
<small>Loaded: {new Date(data.timestamp).toLocaleString('en-US')}</small>
</div>
);
}
// Main component
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>Error handling with use</h2>
<div style={{ marginBottom: '20px' }}>
<label>
<input
type="checkbox"
checked={shouldFail}
onChange={(e) => setShouldFail(e.target.checked)}
/>
Simulate error
</label>
<button
onClick={() => setKey(k => k + 1)}
style={{ marginLeft: '20px' }}
>
Refresh
</button>
</div>
<ErrorBoundary key={key}>
<Suspense fallback={
<div style={{
padding: '20px',
backgroundColor: '#cfe2ff',
border: '1px solid #b6d4fe',
borderRadius: '8px',
color: '#084298'
}}>
Loading data...
</div>
}>
<DataDisplay dataPromise={dataPromise} />
</Suspense>
</ErrorBoundary>
</div>
);
}Changing the key on ErrorBoundary recreates the boundary, which resets the error. Instead of a boundary you can also add .catch() to the promise and return a fallback value.
Practical applications of use
1. Routing system with lazy loading
A simple router combines lazy, Suspense and a context read with use:
import { use, Suspense, lazy, useState, createContext } from 'react';
// Simulation of a routing system
const routes = {
'/': lazy(() => import('./pages/Home')),
'/about': lazy(() => import('./pages/About')),
'/contact': lazy(() => import('./pages/Contact')),
'/profile': lazy(() => import('./pages/Profile'))
};
// Context for routing
const RouteContext = createContext(null);
// Navigation hook
function useNavigation() {
const { navigate } = use(RouteContext);
return navigate;
}
// Page component
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>Loading page...</p>
</div>
</div>
);
}
// Main application
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: 'Home' },
{ path: '/about', label: 'About' },
{ path: '/contact', label: 'Contact' },
{ path: '/profile', label: 'Profile' }
];
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 loads a page's code only on the first visit, and Suspense shows PageLoader meanwhile. This is only a model, because in practice you will use React Router or your framework's router.
2. Dynamic forms with validation
The form keeps its state in context, and the fields read it through use. First the context, the field hook and the FormField component:
import { use, createContext, useState } from 'react';
// Context for the form
const FormContext = createContext(null);
// Hook for form management
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)
};
}
// Form field component
function FormField({ name, label, type = 'text', validate }) {
const field = useFormField(name);
const form = use(FormContext);
// Register validator
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>
);
}
Every field registers its validator and shows its own error. Now the provider that holds the values and runs validation:
// Form provider
function FormProvider({ children, onSubmit }) {
const [values, setValues] = useState({});
const [errors, setErrors] = useState({});
const [validators] = useState({});
const setValue = (name, value) => {
setValues(prev => ({ ...prev, [name]: value }));
// Clear error on value change
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>
);
}
Validators receive a second argument: all form values. That matters in the usage example:
// Usage example
function RegistrationFormExample() {
const handleSubmit = (values) => {
console.log('Form submitted:', values);
alert('Registration completed successfully!');
};
return (
<div style={{ maxWidth: '400px', margin: '0 auto', padding: '20px' }}>
<h2>Registration Form</h2>
<FormProvider onSubmit={handleSubmit}>
<FormField
name="email"
label="Email"
type="email"
validate={(value) => {
if (!value) return 'Email is required';
if (!/\S+@\S+\.\S+/.test(value)) return 'Invalid email';
return '';
}}
/>
<FormField
name="password"
label="Password"
type="password"
validate={(value) => {
if (!value) return 'Password is required';
if (value.length < 8) return 'Password must be at least 8 characters';
return '';
}}
/>
<FormField
name="confirmPassword"
label="Confirm password"
type="password"
validate={(value, allValues) => {
if (value !== allValues.password) return 'Passwords do not match';
return '';
}}
/>
<button
type="submit"
style={{
width: '100%',
padding: '10px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
fontSize: '16px',
cursor: 'pointer'
}}
>
Register
</button>
</FormProvider>
</div>
);
}The "Confirm password" field compares its value with allValues.password. It cannot call use inside the validator, because use only works while a component or hook is rendering, and the validator runs in an event handler.
Best practices with use
1. When to use use
Here are good and bad uses in a nutshell:
// GOOD - conditional usage
function ConditionalData({ showDetails }) {
if (showDetails) {
const details = use(detailsPromise);
return <DetailView details={details} />;
}
return <Summary />;
}
// GOOD - in loops
function MultipleResources({ resourceIds }) {
const resources = [];
for (const id of resourceIds) {
resources.push(use(fetchResource(id)));
}
return <ResourceList resources={resources} />;
}
// BAD - unnecessary use for simple values
function BadExample() {
const value = use(Promise.resolve(42)); // Unnecessary!
return <div>{value}</div>;
}In MultipleResources, the fetchResource function must return a cached Promise, just like fetchPost above.
2. Cache and optimization
The cache can be wrapped in a custom hook:
// Simple cache implementation
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;
}
// Usage
function CachedDataComponent({ userId }) {
const userData = useCachedResource(
`user-${userId}`,
() => fetchUser(userId)
);
return <UserProfile user={userData} />;
}useCachedResource is an ordinary custom hook, and a module-level Map survives between renders.
3. Error handling
Retrying with exponential backoff can be wrapped in a promise factory:
// Wrapper with 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;
};
}
// Usage
function RobustDataFetching() {
const dataPromise = createRetryablePromise(
() => fetch('/api/critical-data').then(res => res.json())
)();
return (
<ErrorBoundary>
<Suspense fallback={<div>Loading...</div>}>
<DataComponent dataPromise={dataPromise} />
</Suspense>
</ErrorBoundary>
);
}Here, too, the Promise is created during render, so in production combine it with a cache.
Recap before the exercises: memo with a custom comparison and the optimization process
The exercises after this lesson come back to memo. By default memo compares every prop shallowly, with Object.is. As the second argument you can pass your own function arePropsEqual(prevProps, nextProps): when it returns true, React treats the props as equal and skips the render, and when it returns false, it renders the component:
import { memo } from 'react';
const TelemetryPanel = memo(function TelemetryPanel({ readings, title }) {
return <Chart data={readings} label={title} />;
}, (prevProps, nextProps) =>
// true = we treat the props as equal, so React skips the render
prevProps.readings.length === nextProps.readings.length && prevProps.title === nextProps.title
);The function does nothing by itself, for example it does not switch on a deep comparison of objects: only what you write in it counts. A mistake in the comparison means a stale screen, so use it rarely.
Each of these techniques is a tool, not a goal. Always optimize in the same order: first a baseline measurement, then profiling, which shows where the render time goes, then identifying the bottleneck and implementing one fix. Finally you measure the impact of the change and run regression tests to check that the app still works as before. You can do these last two steps in either order, as long as you skip neither.
Summary
The use hook opens new possibilities in React, allowing for more flexible management of asynchronous data and context. Its unique ability to be used conditionally and in loops makes it a powerful tool for advanced applications.
My advice: never create a Promise in a client component without a cache. Remember: use is the station's receiver waiting for the probe's report, but the report itself needs one fixed channel.
Code for this lesson: App.jsx
import React, { use, createContext, useState, Suspense } from 'react';
// Space application contexts
const ThemeContext = createContext('dark');
const CrewContext = createContext(null);
// Simulating data fetching from API (Promise)
function fetchMissionData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: 'Andromeda Mission',
status: 'In progress',
crew: 7,
distance: '2.537 million ly',
fuelLevel: 78,
});
}, 1500);
});
}
// Component reading data from Context using use()
function CrewPanel() {
// use() with Context - works like useContext, but can be conditional!
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' }}>
Ship crew
</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>
);
}
// Component reading a Promise using use()
function MissionDetails({ missionPromise }) {
// use() automatically "unwraps" the 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],
['Crew', `${mission.crew} people`],
['Distance', mission.distance],
['Fuel', `${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() can sit in a condition: here we read the context only when the details are visible.
// With useContext such a call after a return statement would not be allowed.
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',
}}>
Details hidden
</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',
}}>
On board: {crew.length} crew members ({crew.map((member) => member.role).join(', ')})
</div>
);
}
function LoadingFallback() {
return (
<div style={{
padding: '40px', textAlign: 'center', color: '#778da9',
}}>
<div style={{ fontSize: '24px', marginBottom: '10px' }}>Loading mission data...</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: 'Captain Nova', role: 'Commander' },
{ id: 2, name: 'Dr. Stella', role: 'Navigator' },
{ id: 3, name: 'Eng. Orion', role: 'Mechanic' },
{ 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 and Context
</h1>
<p style={{ color: '#778da9', textAlign: 'center', marginBottom: '24px', fontSize: '14px' }}>
A new way to read data in 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 ? 'Hide details' : 'Show details'}
</button>
</div>
<ConditionalInfo showDetails={showDetails} />
</div>
</div>
</CrewContext.Provider>
</ThemeContext.Provider>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the purpose of the second argument (custom comparator) in React.memo(Component, compareFn)?
Hands-on tasks in the game
- Vertical ordering
Arrange the performance optimization workflow in order: