DEV Community

Mauricio
Mauricio

Posted on • Edited on

What am I not getting about the useTransition hook?

So, I'm trying to learn how to use the useTransition hook, what I expect this code to do is to disable the button to increment and only enable it after the counter has changed. But the "isPending" is changing rigth after the click (I believe just on the next render).

Gif of a button being and adding +1 to a counter on the top of the screen. Sometimes a small flickering text appears at the bottom

As you can see there is a small flicker of a "Loading..." text on the bottom of the image, and it doesn't wait for the counter to update, what am I missing here? is this not the intended use case for this hook?

Here's the code for the example above

import "./styles.css";
import { useState, useTransition } from "react";

export default function App() {
  const [counter, setCounter] = useState(10);
  const [isPending, startTransition] = useTransition();

  const increment = async () => {
    await new Promise((r) => setTimeout(r, 1000));
    setCounter((e) => e + 1);
  };

  const onClickIncrement = (e) => {
    startTransition(() => {
      increment();
    });
  };

  return (
    <div className="App">
      <h1>{counter}</h1>
      <button disabled={isPending} onClick={onClickIncrement}>
        Click me!
      </button>
      <p>{isPending && <small>Loading...</small>}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)