불필요한 React 구성 요소 다시 렌더링을 방지하는 방법

WBOY
풀어 주다: 2024-09-10 11:09:24
원래의
527명이 탐색했습니다.

How to Prevent Unnecessary React Component Re-Rendering

효율적이고 성능이 뛰어난 애플리케이션을 구축하려면 React Native가 구성 요소를 렌더링하는 방법을 이해하는 것이 필수적입니다. 컴포넌트의 상태나 props가 변경되면 React는 해당 변경 사항을 반영하기 위해 사용자 인터페이스(UI)를 자동으로 업데이트합니다. 결과적으로 React는 구성 요소의 render 메서드를 다시 호출하여 업데이트된 UI 표현을 생성합니다.

이 기사에서는 세 가지 React Hooks와 React에서 불필요한 렌더링을 방지하는 방법을 살펴보겠습니다

  • 메모 사용
  • 콜백 사용
  • Ref 사용

이러한 도구를 사용하면 불필요한 재렌더링을 방지하고 성능을 개선하며 값을 효율적으로 저장하여 코드를 최적화할 수 있습니다.

이 기사를 마치면 이러한 편리한 React 후크를 사용하여 React 애플리케이션을 더 빠르고 반응적으로 만드는 방법을 더 잘 이해할 수 있습니다.

React의 useMemo 사용하기

React에서는 useMemo를 사용하여 불필요한 재렌더링을 방지하고 성능을 최적화할 수 있습니다.

useMemo 후크가 React 구성요소에서 불필요한 재렌더링을 어떻게 방지할 수 있는지 살펴보겠습니다.

useMemo는 함수의 결과를 기억하고 종속성을 추적함으로써 필요한 경우에만 프로세스가 다시 계산되도록 합니다.

다음 예를 고려해보세요.

import { useMemo, useState } from 'react';

    function Page() {
      const [count, setCount] = useState(0);
      const [items] = useState(generateItems(300));

      const selectedItem = useMemo(() => items.find((item) => item.id === count), [
        count,
        items,
      ]);

      function generateItems(count) {
        const items = [];
        for (let i = 0; i < count; i++) {
          items.push({
            id: i,
            isSelected: i === count - 1,
          });
        }
        return items;
      }

      return (
        <div className="tutorial">
          <h1>Count: {count}</h1>
          <h1>Selected Item: {selectedItem?.id}</h1>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }

    export default Page;
로그인 후 복사

위 코드는 useMemo를 사용하여 selectedItem 계산을 최적화하는 Page라는 React 구성 요소입니다.

설명은 다음과 같습니다.

  • 구성요소는 useState 후크를 사용하여 상태 변수 개수를 유지합니다.
  • 항목 상태는 generateItems 함수의 결과와 함께 useState 후크를 사용하여 초기화됩니다.
  • selectedItem은 items.find 작업의 결과를 기억하는 useMemo를 사용하여 계산됩니다. 개수나 항목이 변경된 경우에만 다시 계산됩니다.
  • generateItems 함수는 주어진 개수를 기준으로 항목 배열을 생성합니다.
  • 구성요소는 현재 count 값, selectedItem ID 및 개수를 증가시키는 버튼을 렌더링합니다.

useMemo를 사용하면 items.find 작업의 결과를 메모하여 성능을 최적화합니다. selectedItem의 계산은 종속성(개수 또는 항목)이 변경될 때만 수행되어 후속 렌더링 시 불필요한 재계산을 방지합니다.

메모이제이션은 렌더링 프로세스에 추가 오버헤드를 발생시키므로 계산 집약적인 작업에 선택적으로 사용해야 합니다.

React의 useCallback 사용하기

React의 useCallback 후크를 사용하면 함수를 메모하여 각 구성 요소 렌더링 중에 해당 함수가 다시 생성되는 것을 방지할 수 있습니다. useCallback을 활용합니다. 부품은 한 번만 생성되며 해당 종속성이 변경되지 않는 한 후속 렌더링에서 재사용됩니다.

다음 예를 고려해보세요.

import React, { useState, useCallback, memo } from 'react';

    const allColors = ['red', 'green', 'blue', 'yellow', 'orange'];

    const shuffle = (array) => {
      const shuffledArray = [...array];
      for (let i = shuffledArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
      }
      return shuffledArray;
    };

    const Filter = memo(({ onChange }) => {
      console.log('Filter rendered!');

      return (
        <input
          type='text'
          placeholder='Filter colors...'
          onChange={(e) => onChange(e.target.value)}
        />
      );
    });

    function Page() {
      const [colors, setColors] = useState(allColors);
      console.log(colors[0])

      const handleFilter = useCallback((text) => {
        const filteredColors = allColors.filter((color) =>
          color.includes(text.toLowerCase())
        );
        setColors(filteredColors);
      }, [colors]);


      return (
        <div className='tutorial'>
        <div className='align-center mb-2 flex'>
          <button onClick={() => setColors(shuffle(allColors))}>
            Shuffle
          </button>
          <Filter onChange={handleFilter} />
        </div>
        <ul>
          {colors.map((color) => (
            <li key={color}>{color}</li>
          ))}
        </ul>
      </div>
      );
    }

    export default Page;
로그인 후 복사

위 코드는 React 구성 요소의 간단한 색상 필터링 및 셔플링 기능을 보여줍니다. 단계별로 살펴보겠습니다.

  • 초기 색상 배열은 allColors로 정의됩니다.
  • shuffle 함수는 배열을 가져와 해당 요소를 무작위로 섞습니다. Fisher-Yates 알고리즘을 사용하여 셔플링을 수행합니다.
  • Filter 컴포넌트는 입력 요소를 렌더링하는 메모화된 기능 컴포넌트입니다. onChange prop을 받아 입력 값이 변경되면 콜백 함수를 트리거합니다.
  • 페이지 구성 요소는 색상 필터링 및 셔플링 기능을 렌더링하는 주요 구성 요소입니다.
  • 상태 변수 colors는 useState 후크를 사용하여 초기화되며 초기 값은 allColors로 설정됩니다. 필터링된 색상 목록을 나타냅니다.
  • handleFilter 함수는 useCallback 후크를 사용하여 생성됩니다. 텍스트 매개변수를 사용하고 제공된 텍스트를 기반으로 allColors 배열을 필터링합니다. 필터링된 색상은 useState 후크의 setColors 함수를 사용하여 설정됩니다. 종속성 배열 [colors]는 색상 상태가 변경되는 경우에만 handlerFilter 함수가 다시 생성되도록 보장하여 불필요한 재렌더링을 방지하여 성능을 최적화합니다.
  • 페이지 구성 요소 내부에는 색상을 섞는 버튼이 있습니다. 버튼을 클릭하면 섞인 allColors 배열과 함께 setColors 함수가 호출됩니다.
  • Filter 구성요소는 onChange prop이 handlerFilter 함수로 설정된 상태로 렌더링됩니다.
  • 마지막으로 색상 배열이 매핑되어 색상 항목 목록을
  • 으로 렌더링합니다.
  • 요소.

useCallback 후크는 handlerFilter 함수를 기억하는 데 사용됩니다. 즉, 함수는 한 번만 생성되고 종속성(이 경우 색상 상태)이 동일하게 유지되는 경우 후속 렌더링에서 재사용됩니다.

This optimization prevents unnecessary re-renders of child components that receive the handleFilter function as a prop, such as the Filter component.
It ensures that the Filter component is not re-rendered if the colors state hasn't changed, improving performance.

Using React's useRef

Another approach to enhance performance in React applications and avoid unnecessary re-renders is using the useRef hook. Using useRef, we can store a mutable value that persists across renders, effectively preventing unnecessary re-renders.

This technique allows us to maintain a reference to a value without triggering component updates when that value changes. By leveraging the mutability of the reference, we can optimize performance in specific scenarios.

Consider the following example:

import React, { useRef, useState } from 'react';

function App() {
  const [name, setName] = useState('');
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <div>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        ref={inputRef}
      />
      <button onClick={handleClick}>Focus</button>
    </div>
  );
}
로그인 후 복사

The example above has a simple input field and a button. The useRef hook creates a ref called inputRef. As soon as the button is clicked, the handleClick function is called, which focuses on the input element by accessing the current property of the inputRef ref object. As such, it prevents unnecessary rerendering of the component when the input value changes.

To ensure optimal use of useRef, reserve it solely for mutable values that do not impact the component's rendering. If a mutable value influences the component's rendering, it should be stored within its state instead.

Conclusion

Throughout this tutorial, we explored the concept of React re-rendering and its potential impact on the performance of our applications. We delved into the optimization techniques that can help mitigate unnecessary re-renders. React offers a variety of hooks that enable us to enhance the performance of our applications. We can effectively store values and functions between renders by leveraging these hooks, significantly boosting React application performance.

위 내용은 불필요한 React 구성 요소 다시 렌더링을 방지하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!