Skip to main content

how to use useTransition hook explained with example

ยท 2 min read
Parth Maheta

The useTransition hook in React is also part of Concurrent Mode features, specifically designed to handle asynchronous updates and transitions. It's often used in combination with Suspense to manage the UI transition states.

Let's explore an example of using useTransition:

import React, { useState, useTransition, Suspense } from 'react';

// Simulate an asynchronous data fetching function
const fetchData = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve('Data loaded!');
}, 2000);
});
};

// AsyncComponent that displays fetched data
const AsyncComponent = () => {
const [data, setData] = useState(null);
const [startTransition, isPending] = useTransition({ timeoutMs: 2000 });

// Function to trigger the data fetching
const fetchDataAsync = () => {
startTransition(() => {
fetchData().then(result => {
setData(result);
});
});
};

return (
<div>
<button onClick={fetchDataAsync} disabled={isPending}>
Fetch Data
</button>

<Suspense fallback={<p>Loading...</p>}>
{/* Display the fetched data when available */}
{data && <p>{data}</p>}
</Suspense>
</div>
);
};

export default AsyncComponent;

In this example:

  • The useTransition hook is used to manage the transition state. It returns an array with two elements: the startTransition function and a boolean value isPending indicating whether a transition is in progress.
  • Clicking the "Fetch Data" button triggers the fetchDataAsync function, which uses startTransition to initiate the asynchronous data fetching. The isPending value can be used to disable the button during the transition.
  • The Suspense component is used to wrap the content that depends on the asynchronous data. It provides a fallback UI (<p>Loading...</p>) while the data is being fetched.

This example demonstrates how useTransition helps manage the transition state during asynchronous operations, ensuring a smoother user experience.