Home > Web Front-end > JS Tutorial > body text

React Basics~Render Performance/ useTransition

Susan Sarandon
Release: 2024-10-18 08:35:29
Original
763 people have browsed it
  • Suppose that we are displaying a large number of data, such as 10thousands of data, there is often a delay in puuting next value to the input field.

  • In this case, when we enter a value, the screen displays filtered data.

  • But then, a problem that occurs is the delay in displaying the next action such as input next value to input field due to handling too much data.

・src/Example.js

import { useState } from "react";

const generateDummyItem = (num) => {
  return new Array(num).fill(null).map((item, index) => `item ${index}`);
};

const dummyItems = generateDummyItem(10000);

const Example = () => {
  const [filterVal, setFilterVal] = useState("");

  const changeHandler = (e) => {
      setFilterVal(e.target.value);
  };

  return (
    <>
      <input type="text" onChange={changeHandler} />
      {isPending && <div>Loading...</div>}
      <ul>
        {dummyItems
          .filter((item) => {
            if (filterVal === "") return true;
            return item.includes(filterVal);
          })
          .map((item) => (
            <li key={item}>{item}</li>
          ))}
      </ul>
    </>
  );
};

export default Example;

Copy after login
  • To solve the problem, we can wrap the setFilterVal function with a startTransition.
  const changeHandler = (e) => {
    startTransition(() => {
      setFilterVal(e.target.value);
    })
  };
Copy after login
  • The startTransition makes a function delay to be executed within it.

  • Thanks to this feature, we can easily move on to the next value in the input field.

・Before input
React Basics~Render Performance/ useTransition

・After input
React Basics~Render Performance/ useTransition

The above is the detailed content of React Basics~Render Performance/ useTransition. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!