React 기초~렌더링 성능/메모

DDD
풀어 주다: 2024-10-14 16:35:31
원래의
860명이 탐색했습니다.
  • 하위 구성 요소가 렌더링되는 패턴입니다.
  1. 상위 구성 요소가 다시 렌더링되는 경우(예: 자체 상태 업데이트 등)

  2. 자식 컴포넌트의 props를 다시 렌더링할 때

그러나 실제로는 하위 구성 요소를 다시 렌더링하기 위해 props를 렌더링할 때만 필요합니다. 그 밖의 모든 것은 불필요합니다.

・src/Example.js

mport React, { useState } from "react";
import Child from "./Child";
import "./Example.css";

const Example = () => {
  console.log("Parent render");
  const [countA, setCountA] = useState(0);
  const [countB, setCountB] = useState(0);
  return (
    <div className="parent">
      <div>
        <h3>Parent Component</h3>
        <div>
          <button
            onClick={() => {
              setCountA((pre) => pre + 1);
            }}
          >
            Button A
          </button>
          <span>Update the state of Parent Component</span>
        </div>
        <div>
          <button
            onClick={() => {
              setCountB((pre) => pre + 1);
            }}
          >
            Buton B
          </button>
          <span>Update the state of Child Component</span>
        </div>
      </div>
      <div>
        <p>The count of clicked:{countA}</p>
      </div>
      <Child countB={countB} />
    </div>
  );
};

export default Example;
로그인 후 복사

・src/Child .js

const Child = ({ countB }) => {
  console.log("%cChild render", "color: red;");

  return (
    <div className="child">
      <h2>Child component</h2>
      <span>The count of B button cliked:{countB}</span>
    </div>
  );
};

export default Child;

로그인 후 복사
  • 이 경우 A(Parent 컴포넌트) 버튼을 누르면 자식 컴포넌트가 렌더링됩니다. 불필요한데도요.

・이렇게
React Basics~Render Performance/ memo

・src/Child .js (메모훅 사용)

import { memo } from "react";

function areEqual(prevProps, nextProps) {
  if (prevProps.countB !== nextProps.countB) {
    return false; // re-rendered
  } else {
    return true; // not-re-rendred
  }
}

const ChildMemo = memo(({ countB }) => {
  console.log("%cChild render", "color: red;");

  return (
    <div className="child">
      <h2>Child component</h2>
      <span>The count of B button cliked:{countB}</span>
    </div>
  );
}, areEqual);

export default ChildMemo;

로그인 후 복사
  • 메모를 이용하면 불필요한 재렌더링을 피할 수 있습니다.

・이렇게
React Basics~Render Performance/ memo

위 내용은 React 기초~렌더링 성능/메모의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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