Sub topic 1
React Concurrent Features: Transitions and Deferred Values
Prerequisites
This chapter assumes solid knowledge of React function components, JSX, useState, props, and re-rendering. React 18 or later is also assumed.
Urgent and non-urgent updates
An urgent update needs to appear immediately. Typing into a controlled input, pressing a button, and moving a pointer are common examples. Delaying these updates makes the interface feel broken.
A non-urgent update can appear shortly after the user's action. Rendering a large search result list or switching to a data-heavy tab often fits this category. The result still matters, but it should not block the urgent interaction.
React lets you mark non-urgent state updates as transitions. This tells React that it may pause, restart, or abandon that rendering work when a more urgent update arrives.
How concurrent rendering keeps the UI responsive
Concurrent rendering is React's ability to work on a render in interruptible pieces. It does not mean that JavaScript runs on multiple threads. React still runs on the browser's JavaScript thread.
React first calculates the next UI. It can pause that calculation to process urgent work, then continue later. React changes the browser DOM only after it has a consistent result, so users do not see a half-committed render.
A transition improves scheduling, not raw rendering speed. If the expensive component still takes too long to render, you may also need virtualization, memoization, or less data.
Opting in with createRoot
React 18 enables concurrent features when you mount the application with createRoot:
import { createRoot } from 'react-dom/client';
import App from './App';
const root = createRoot(document.getElementById('root'));
root.render(<App />);Older ReactDOM.render mounting does not provide the React 18 concurrent behavior expected by transitions.
Marking updates as transitions with startTransition
Use startTransition when the state update itself is non-urgent:
import { useState, startTransition } from 'react';
function Tabs({ tabs }) {
const [selected, setSelected] = useState(tabs[0]);
function selectTab(tab) {
startTransition(() => {
setSelected(tab);
});
}
return (
<>
{tabs.map((tab) => (
<button key={tab} onClick={() => selectTab(tab)}>
{tab}
</button>
))}
<TabContent name={selected} />
</>
);
}Keep the urgent update outside the transition. For example, update an input's displayed value immediately, then transition the expensive filtering update.
Exercise
Why should a controlled input's value usually be updated urgently instead of inside startTransition?
Show answer
The input must reflect each keystroke immediately. Transitioning its value can make typing feel delayed or cause React to reject the update.