>  기사  >  웹 프론트엔드  >  React 기본~렌더링 성능/ useTransition

React 기본~렌더링 성능/ useTransition

Susan Sarandon
Susan Sarandon원래의
2024-10-18 08:35:29765검색
  • 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.