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

Reactの基礎〜レンダリングパフォーマンス/メモ

DDD
DDDオリジナル
2024-10-14 16:35:31863ブラウズ
  • これらは、子コンポーネントがレンダリングされるパターンです。
  1. 親コンポーネントが再レンダリングされるとき (たとえば、それ自体の状態を更新するときなど)。

  2. 子コンポーネントの 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(親コンポーネント)ボタンを押すと、子コンポーネントがレンダリングされます。余計なことなのに

・こんな感じです
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 中国語 Web サイトの他の関連記事を参照してください。

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