This example demonstrates a real use case for `useTransition` in React 18.
Typing into the input updates the text immediately (urgent state), while filtering and rendering a large list of 10,000 items is marked as a transition (non-urgent).
React can delay or interrupt the heavy re-render, keeping the input responsive and showing a pending indicator during the transition.
No fake CPU loops are used — the cost comes from real React rendering.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<style>
body {
font-family: sans-serif;
padding: 20px;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function App() {
const [input, setInput] = React.useState("");
const [query, setQuery] = React.useState("");
const [isPending, startTransition] = React.useTransition();
// Create 10,000 items (actual rendering cost, no fake loops)
const bigList = React.useMemo(
() => Array.from({ length: 10000 }, (_, i) => "Item " + i),
[]
);
const filtered = React.useMemo(() => {
return bigList.filter((item) =>
item.toLowerCase().includes(query.toLowerCase())
);
}, [query]);
function handleChange(e) {
const value = e.target.value;
setInput(value); // urgent update
startTransition(() => {
setQuery(value); // non-urgent (heavy re-render)
});
}
return (
<div>
<h3>React 18 useTransition Demo</h3>
<input
value={input}
onChange={handleChange}
placeholder="Type to filter..."
style={{ padding: "8px", width: "300px" }}
/>
{isPending && (
<span style={{ marginLeft: "10px" }}>Updating…</span>
)}
<ul
style={{
height: "300px",
overflow: "auto",
border: "1px solid #ccc",
marginTop: "10px",
padding: "10px"
}}
>
{filtered.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
</script>
</body>
</html>