javascript / intermediate
Snippet
Non-Blocking UI with useTransition
useTransition allows you to mark state updates as non-blocking 'transitions'. This ensures that urgent updates (like typing in an input) remain responsive while slower updates (like filtering a large list) happen in the background.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { useState, useTransition } from 'react';export function FilterableList({ items }) {const [isPending, startTransition] = useTransition();const [filter, setFilter] = useState('');const handleChange = (e) => {const val = e.target.value;setFilter(val); // High priority updatestartTransition(() => {// Lower priority update// Expensive filtering logic here});};return <input type="text" onChange={handleChange} />;}
nextjs
Breakdown
1
const [isPending, startTransition] = useTransition();
Returns a pending state and a function to start a transition.
2
startTransition(() => { ... });
Wraps the low-priority state update to prevent UI blocking.
3
isPending
Can be used to show a loading indicator during the transition.