How To Use useTransition Hook In React? Complete Example Guide

What Is useTransition?

The useTransition hook lets you mark state updates as non-urgent, allowing React to keep the UI responsive during heavy updates.


Basic Syntax

const [isPending, startTransition] = useTransition();
  • isPending → indicates if the transition is ongoing
  • startTransition → wraps non-urgent state updates

Example: Smooth Input Filtering

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

function App() {
  const [text, setText] = useState("");
  const [list, setList] = useState([]);
  const [isPending, startTransition] = useTransition();

  const handleChange = (e) => {
    const value = e.target.value;
    setText(value);

    startTransition(() => {
      const filtered = Array.from({ length: 10000 }, (_, i) => i).filter(
        (n) => n.toString().includes(value)
      );
      setList(filtered);
    });
  };

  return (
    <div>
      <input type="text" value={text} onChange={handleChange} />
      {isPending ? <p>Loading...</p> : <p>Results: {list.length}</p>}
    </div>
  );
}

export default App;

✅ UI remains responsive even during heavy filtering.


Key Points

  • Marks updates as non-urgent
  • Prevents UI blocking during large renders
  • isPending helps show loading indicators
  • Ideal for search, filtering, or heavy computation

Conclusion

useTransition helps React apps remain fast and responsive, even during high-cost updates or heavy computations.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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