ReactJS Hook To Combine useTransition And useState Using use-transition-state


Category: React React Others | July 6, 2021
Author:wellyshen
Official Page:Go to website
Last Update:July 6, 2021
License:MIT

Description:

use-transition-state hook builds on top of React.useTransition to reduce the verbose of using in conjunction with React.useState.

Please note that, this hook requires React Version 18.0.0 or greater.

How can I use it?

Step1: First, install the hook with NPM or Yarn.

#NPM
npm install --save use-transition-state

#Yarn
yarn add use-transition-state

Step2: Import the hook.

import { useState, useTransition } from "react";

Step3: Here is the code that will give you an idea how it works.

const App = () => {
  const [searchQuery, setSearchQuery] = useState(null);
  const [isPending, startTransition] = useTransition({ timeoutMs: 500 });

  const handleInputChange = (e) => {
    startTransition(() => {
      setSearchQuery(getParsedData(e.target.value));
    });
  };

  return (
    <div>
      <input onChange={handleInputChange} />
      {isPending && "Loading..."}
      <div>{searchQuery || "Start search"}</div>
    </div>
  );
};