・This pattern enables us to perform updates as non-urgent transitions. This keeps the UI responsive by enabling React to interrupt updates for more urgent ones, and provides a loading state that can be used to show users feedback.
import { useState, useTransition } from "react";
async function asyncFunction(input) {
await new Promise((resolve) => setTimeout(resolve, 3000));
return input;
}
function App() {
const [input, setInput] = useState("");
const [result, setResult] = useState("");
const [isPending, startTransition] = useTransition();
const handleTransition = async () => {
startTransition(async () => {
const asyncResult= await asyncFunction(input);
startTransition(() => setResult(asyncResult))
});
};
return (
<div>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<button onClick={handleTransition}>Transition</button>
{isPending && <p>Loading...</p>}
{result && <p>{result}</p>}
</div>
);
}
export default App;
Top comments (0)