React · Lesson 70 of 120
useTransition
Stay responsive.
Some updates are urgent, like typing or clicking. Others can wait, like drawing a big new page. Transitions tell React which updates aren't urgent, so the page stays responsive.
- Urgent updates
- Updates that can wait
- Transitions
A slow tab
Slow list takes a while to render. Start transition marks the tab change as not urgent. React keeps the page responsive, and can interrupt that render if the user clicks again. Is pending is true while it's working, so we show a hint. We open the bikes tab. Run it.
App.jsxjsx
import { useState, useTransition } from "react";
function SlowList() {
const start = performance.now();
while (performance.now() - start < 300) {} // pretend this is slow
return <ul>{["Trail 500", "City 200", "Volt 7"].map(b => <li key={b}>{b}</li>)}</ul>;
}
export default function App() {
const [tab, setTab] = useState("home");
const [isPending, startTransition] = useTransition();
function select(next) {
startTransition(() => setTab(next));
}
return (<div>
<button onClick={() => select("home")}>Home</button>
<button id="bikes" onClick={() => select("bikes")}>Bikes {isPending && "(loading...)"}</button>
{tab === "home" ? <h2>Welcome</h2> : <SlowList />}
</div>);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#bikes"}, {"wait": 800}]Urgent or not
Typing, clicking, and pressing keys should feel instant, so they're urgent. Switching to a heavy tab, or showing a big list, can happen in a transition.
Urgent
- TypingClickingInstant feedback
Transition
- Heavy pagesBig listsCan be interrupted
Summary
Wrap non urgent updates in start transition, to keep the page responsive. Next, use deferred value.
Key takeaways- useTransition
- startTransition
- isPending
Next up: useDeferredValue — lagging on purpose