首頁 > web前端 > js教程 > 主體

React 基礎~渲染效能/ useCallback

Linda Hamilton
發布: 2024-10-16 22:44:02
原創
507 人瀏覽過
  • Even if the memo is set to a child component, the child component can still be re-rendered.

  • It is a case that we pass a function as a props to the child component.

・src/Example.js

import React, { useCallback, useState } from "react";
import Child from "./Child";

const Example = () => {
  console.log("Parent render");

  const [countA, setCountA] = useState(0);
  const [countB, setCountB] = useState(0);

  const clickHandler = () => {
    setCountB((pre) => pre + 1);
  };

  return (
    <div className="parent">
      <div>
        <h3>Parent component</h3>
        <div>
          <button
            onClick={() => {
              setCountA((pre) => pre + 1);
            }}
          >
            button A
          </button>
          <span>Update parent component</span>
        </div>
      </div>
      <div>
        <p>The count of click button A:{countA}</p>
      </div>
      <Child countB={countB} onClick={clickHandler} />
    </div>
  );
};

export default Example;


登入後複製

・src/Child.js

import { memo } from "react";

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

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

export default ChildMemo;


登入後複製
  • The reason the child component is re-rendered is because of the clickHandler function in src/Example.js
  const clickHandler = () => {
    setCountB((pre) => pre + 1);
  };
登入後複製
  • This function is passed to the child component as an onClick props.
 <Child countB={countB} onClick={clickHandler} />
登入後複製
  • If we wrap the child component with a useCallback, we can avoid this case.
  const clickHandler = useCallback(() => {
    setCountB((pre) => pre + 1);
  }, []);
登入後複製

React Basics~Render Performance/ useCallback

React Basics~Render Performance/ useCallback

以上是React 基礎~渲染效能/ useCallback的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!