Sub topic 2
useTransition and the isPending Flag
Assume you know function components, JSX, useState, and how React re-renders components. React concurrent features let React pause expensive rendering so urgent work, such as typing, can finish first.
useTransition and `isPending`
useTransition returns two values:
isPending, a Boolean that says whether a transition is rendering.startTransition, a function that marks state updates as non-urgent.
Use startTransition for the expensive result, but update the input itself urgently:
import { useState, useTransition } from 'react';
function Search({ items }) {
const [text, setText] = useState('');
const [filter, setFilter] = useState('');
const [isPending, startTransition] = useTransition();
function handleChange(event) {
const nextText = event.target.value;
setText(nextText);
startTransition(() => {
setFilter(nextText);
});
}
const results = items.filter((item) => item.includes(filter));
return (
<>
<input value={text} onChange={handleChange} />
{isPending && <p>Updating results...</p>}
<ul>
{results.map((item) => <li key={item}>{item}</li>)}
</ul>
</>
);
}React can interrupt the filtering render when another keystroke arrives. The input remains responsive while React works on the list.
Showing pending and stale content
isPending describes a transition started in the current component. Use it to show a message, dim old content, or disable an action.
A transition does not automatically show a loading screen. The current UI usually remains visible until the new render completes. This avoids replacing useful content with a blank intermediate state.
Deferring a value with `useDeferredValue`
useDeferredValue returns a value that may temporarily lag behind its latest version. This is useful when a parent owns the urgent state but a child renders expensive content.
import { memo, useDeferredValue, useState } from 'react';
const SlowList = memo(function SlowList({ query, items }) {
return (
<ul>
{items
.filter((item) => item.includes(query))
.map((item) => <li key={item}>{item}</li>)}
</ul>
);
});
export default function App({ items }) {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<SlowList query={deferredQuery} items={items} />
</>
);
}Why the child must be memoized
The parent re-renders immediately when query changes. Without memo, SlowList also renders immediately, even when it receives the same deferred value. memo lets React skip that child render until deferredQuery changes.
Exercise
Which value should a controlled input use: the current state or its deferred version?
Show answer
Use the current state. Defer the expensive content that responds to the input.