How to Use useTransition Hook in React – with Examples

how-to-use userransition-hook-in-react

In the dynamic world of web development, creating smooth and seamless user interfaces is essential for enhancing user experience. React, being one of the most popular JavaScript libraries, offers various hooks to streamline UI development.

Among them, the useTransition hook stands out as a powerful tool for managing transitions and animations effectively without blocking the user interface. In this blog, we will explore the useTransition hook, its benefits, and how to implement it in your React applications.

Table of Contents

What is useTransition?

The useTransition hook is a relatively new addition to React’s collection of hooks, introduced in React version 18. It is designed to manage complex UI transitions by allowing you to defer the rendering of certain components. By doing so, it helps to prevent performance bottlenecks and improve the user experience during intense updates or transitions.

The primary goal of useTransition is to enable React applications to stay responsive and maintain smooth animations even during heavy operations, such as data fetching, large-scale updates, or any process that might cause the UI to freeze temporarily.

Benefits of useTransition

  1. Improved User Experience: By using useTransition, developers can ensure that the application remains responsive and interactive during resource-intensive tasks, leading to a better overall user experience.
  2. Smooth Animations: With useTransition, you can create smooth animations that run seamlessly, without blocking the user interface.
  3. Better Performance: By deferring rendering and updates, the useTransition hook helps prevent unnecessary re-renders and optimizes performance.
  4. Enhanced Code Maintainability: useTransition simplifies the management of complex animations and transitions, making the codebase cleaner and more maintainable.

How to Use useTransition?

Let’s walk through a step-by-step guide on how to use the useTransition hook in your React application.

Step 1: Update to React version 18 (or higher)

Before using the useTransition hook, ensure that your React application is running on version 18 or higher. This hook was introduced in React 18, so you need to update your project’s dependencies accordingly.

Step 2: Import the hook

To use the useTransition hook, import it from the react package.

import { useTransition } from 'react';

Step 3: Define the Transition

Next, define the transition using the useTransition hook. The hook requires two arguments: the resource-intensive function and a configuration object.

const [startTransition, isPending] = useTransition();

Step 4: Implement the Transition

Now, you can use the startTransition function to initiate the transition or resource-intensive operation. This function takes a callback function that contains the resource-intensive task.

const fetchData = () => {
  // Perform the resource-intensive operation (e.g., fetching data from an API)
};

const handleButtonClick = () => {
  startTransition(() => {
    fetchData();
  });
};

Step 5: Render the Pending Component

During the transition or while the resource-intensive task is being executed, you can display a “loading” or “pending” component to provide feedback to the user. You can use the isPending value returned by the useTransition hook to conditionally render this component.

const App = () => {
  return (
    <div>
      {/* Your main components */}
      {isPending && <LoadingComponent />}
    </div>
  );
};

Example: Infinite Scrolling with useTransition

Imagine you have a web application that displays a list of items retrieved from an API. As the user scrolls down, the application fetches additional data to load more items dynamically.

To provide a smooth user experience, you want to use the useTransition hook to handle the loading state and animations during data fetching.

Step 1: Create a new React App

First, you need to create a new React app. To do this, follow the tutorial How to Create Your First ReactJS App: Hello World Example.

Create a new react app with the name infinite-scroll. Follow all the instructions to remove unwanted files from the project. Make sure you keep the App.js file and do not delete it as mentioned in the above blog instruction.

Step 2: Make sure to have the below code in the given files

index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

App.js

function App() {
  return <h1>Hello World</h1>;
}
export default App;

index.css – Remove everything from this file. We will add CSS styling later.

Step 3: Set up the Component

In App.js file, create a component that will display the list of items and handle the infinite scrolling behavior.

import React, { useState, useEffect } from "react";
import { useTransition } from "react";

function App() {
  const [items, setItems] = useState([]);
  const [page, setPage] = useState(1);
  const [isFetching, setIsFetching] = useState(false);
  const [isPending, startTransition] = useTransition();

  const fetchMoreData = () => {
    setTimeout(() => {
      fetch(`https://api.instantwebtools.net/v1/passenger?page=${page}&size=10`)
        .then((response) => response.json())
        .then((data) => {
          setItems((prevItems) => [...prevItems, ...data["data"]]);
          setIsFetching(false);
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
          setIsFetching(false);
        });
    }, 1000);
  };

  useEffect(() => {
    if (isFetching) {
      startTransition(() => {
        fetchMoreData();
      });
    }
  }, [isFetching, startTransition]);

  const handleScroll = () => {
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;
    const scrollTop = window.scrollY;

    if (scrollTop + windowHeight >= documentHeight) {
      setIsFetching(true);
      setPage((prevPage) => prevPage + 1);
    }
  };

  useEffect(() => {
    fetchMoreData();
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  return (
    <div>
      <div className="container">
        {items.map((item, index) => {
          return (
            <div className="card" key={item._id}>
              <p>{item.name}</p>
              <p>{item.trips}</p>
            </div>
          );
        })}
      </div>
      {isPending && <div>Loading more items...</div>}
    </div>
  );
}

export default App;

Update index.css for some basic styling.

* {
  margin: 0;
  padding: 0;
}

body {
  box-sizing: border-box;
}

.container {
  width: 30%;
  margin: auto;
}

.card {
  padding: 5px 10px;
  border: 1px solid #000;
  border-radius: 8px;
  margin: 20px 0;
  background-color: lightblue;
}

When you run the app, the output will show like the below image.

usetransition-hook

Try to scroll the page down, you will see more records will load when you scroll down.

Note: This is a free API from https://www.instantwebtools.net so similar data is fetched. However, you can use your own API to test it.

In this example, we have a component called InfiniteScrollList, which displays a list of items fetched from an API. As the user scrolls down, the handleScroll function is triggered, and it sets the isFetching state to true to indicate that more data needs to be loaded.

Conclusion

The useTransition hook in React empowers developers to create smooth UI transitions and animations while maintaining a responsive user interface, even during resource-intensive tasks. By deferring rendering and optimizing performance, useTransition significantly enhances the overall user experience. Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top