ホームページ  >  記事  >  ウェブフロントエンド  >  React の基本~レンダリング パフォーマンス/ useTransition

React の基本~レンダリング パフォーマンス/ useTransition

Susan Sarandon
Susan Sarandonオリジナル
2024-10-18 08:35:29766ブラウズ
  • 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;

  • To solve the problem, we can wrap the setFilterVal function with a startTransition.
  const changeHandler = (e) => {
    startTransition(() => {
      setFilterVal(e.target.value);
    })
  };
  • 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

以上がReact の基本~レンダリング パフォーマンス/ useTransitionの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。