DEV Community

Cover image for useTransition hook in React 19
Majd Hemud
Majd Hemud

Posted on • Edited on

useTransition hook in React 19

React 19 is finally here! Bringing new features and APIs to the frontend world and for all React lovers. To create smoother, faster, and more efficient React apps.

In this Article we will talk about useTransition hook in React 19 😁

The useTransition hook

This hook is your secret weapon to handle slow state updates without freezing the UI. Which is really cool when dealing with data fetching or expensive computations.

In React 19 you can now directly pass an asynchronous function (like async/await) to startTransition function. This allows you to perform an asynchronous operation(e.g., API call) within the transition itself, simplifying your code and making it easier to manage the transition state.

Example:

import { useState, useTransition } from 'react';

async function fetchCarsData() {
  try {
    // Simulate delay
    await new Promise((resolve) => setTimeout(resolve, 4000));

    // Replace this with your actual static data
    return [
      { id: 1, name: "BMW" },
      { id: 2, name: "Nissan" },
      { id: 3, name: "Honda" },
    ];
  } catch (error) {
    throw error;
  }
}

function CarList() {
  const [error, setError] = useState(null);
  const [cars, setCars] = useState([]);
  const [isPending, startTransition] = useTransition();

  const handleClick = async () => {
    startTransition(async () => {
      fetchCarsData().then((data) => setCars(data))
      .catch((error) => setError(error.message)); 
    });
  };

  return (
    <div>
      <button disabled={isPending} onClick={handleClick}>
        {isPending ? "Loading..." : "Load Cars"}
      </button>
      {error ? (
        <p style={{ color: "red" }}>Error: {error}</p>
      ) : isPending ? (
        <p>Loading...</p>
      ) : cars.length > 0 ? (
        <ul>
          {cars.map((car) => (
            <li key={car.id}>{car.name}</li>
          ))}
        </ul>
      ) : (
        <p>No cars loaded yet.</p>
      )}
    </div>
  );
}

export default CarList;
Enter fullscreen mode Exit fullscreen mode

In the example above, the fetchCarsData function is wrapped in startTransition function. This ensures that the UI remains responsive even during the API call. Plus we used the isPending flag to know if there is a pending transition.

Things to avoid when using useTransition hook

  • Avoid using useTransition hook for state changes that control input elements (text fields, etc.). These need immediate updates for a good user experience.

  • Use useTransition hook strategically for non-critical tasks that might cause lags, not for everything.

  • Be aware that currently multiple transitions might run together, which could affect their timing.

  • Profile your app to identify bottlenecks before applying useTransition hook.

  • User interactions always take priority over transitions.

Conclusion

While the useTransition hook offers performance benefits, it requires careful consideration. It functions like a queue for non-critical updates, prioritizing responsiveness during user interactions.

Excessive use can overload this queue, leading to delayed updates for both queued tasks and the overall application. It's best to use it strategically for tasks that can genuinely benefit from a slight delay without impacting the user experience.

I hope you enjoyed reading the article. If you have any questions, thoughts, or just want to say hello, I'd be thrilled to hear from you. Here's how you can reach out:

Drop me an Email: majd.hemud@gmail.com

Follow me 🥰

Explore My Portfolio

If you want to see more of my work, don't forget to check out my portfolio website! There, you'll find a curated collection of my projects, creative endeavors, and a deeper dive into my skills and passions 🔥.

Whether you're looking for design inspiration, curious about my past projects, or just want to connect, my portfolio is the place to be.

Until next time peace ✌️🥰.

Top comments (0)