DEV Community

Cover image for Simplifying React Hooks: useTransition ๐Ÿ’ฏ
Ali Samir
Ali Samir

Posted on

Simplifying React Hooks: useTransition ๐Ÿ’ฏ

React introduced useTransition as one of its concurrent features to enhance performance when dealing with state updates that may cause UI delays. This article will show how useTransition works and demonstrate how to use it effectively with TypeScript.


๐Ÿš€ What is useTransition?

useTransition is a built-in React Hook that allows you to mark certain state updates as non-blocking, ensuring a smoother UI experience.

This is particularly useful for optimizing user interactions where updates might be computationally expensive or cause noticeable UI lag.


โšก Why Use useTransition?

  • Prevents UI blocking during expensive state updates.

  • Enhances performance by prioritizing urgent updates over transitions.

  • Provides a built-in mechanism for tracking pending transitions.


๐Ÿ› ๏ธ Syntax of useTransition

The useTransition hook returns a tuple containing:

  • A boolean (isPending) that indicates whether a transition is in progress.

  • A function (startTransition) that wraps non-urgent updates.

const [isPending, startTransition] = useTransition();
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ฅ Practical Example with TypeScript

Let's say we have a search input that filters a large dataset. Instead of updating the UI immediately (which can cause lag), we use useTransition to mark the filtering operation as a low-priority update.

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

const LargeListFilter: React.FC = () => {
  const [query, setQuery] = useState("");
  const [filteredData, setFilteredData] = useState<string[]>([]);
  const [isPending, startTransition] = useTransition();

  const data = Array.from({ length: 10000 }, (_, i) => `Item ${i + 1}`);

  const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
    setQuery(event.target.value);
    startTransition(() => {
      setFilteredData(
        data.filter((item) => item.toLowerCase().includes(event.target.value.toLowerCase()))
      );
    });
  };

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={handleSearch}
        placeholder="Search items..."
      />
      {isPending && <p>Loading...</p>}
      <ul>
        {filteredData.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </div>
  );
};

export default LargeListFilter;
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ Key Takeaways

  1. Optimized Performance: useTransition ensures that the UI remains responsive while performing expensive operations.

  2. Improved User Experience: Users donโ€™t experience noticeable UI freezes when interacting with the app.

  3. Simple API: With just two values (isPending and startTransition), you can manage UI responsiveness effectively.


โšก When to Use useTransition

  • Filtering/searching large datasets.

  • Rendering heavy UI components.

  • Fetching and displaying large amounts of data.

  • Any scenario where UI blocking due to state updates needs to be minimized.


๐ŸŽฏ Conclusion

The useTransition hook is a powerful tool in Reactโ€™s concurrent rendering model that helps prevent UI blocking while handling complex state updates. Using it with TypeScript ensures type safety and a better development experience.

By integrating useTransition, you can create smoother, more responsive applications that prioritize user experience. ๐Ÿš€


๐ŸŒ Connect With Me On:

๐Ÿ“ LinkedIn
๐Ÿ“ X (Twitter)
๐Ÿ“ Telegram
๐Ÿ“ Instagram

Happy Coding!

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series ๐Ÿ“บ

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series ๐Ÿ‘€

Watch the Youtube series

๐Ÿ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someoneโ€™s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay