React Basics~Render Performance/ useCallback

  • 即使将备忘录设置为子组件,子组件仍然可以重新渲染。

  • 这是一种我们将函数作为 props 传递给子组件的情况。

・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}"></child>
</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;


  • 子组件重新渲染的原因是因为src/example.js中的clickhandler函数
  const clickhandler = () => {
    setcountb((pre) => pre + 1);
  };
  • 此函数作为 onclick 属性传递给子组件。
 <child countb="{countb}" onclick="{clickhandler}"></child>
  • 如果我们用 usecallback 包装子组件,我们可以避免这种情况。
  const clickHandler = useCallback(() => {
    setCountB((pre) => pre + 1);
  }, []);

React Basics~Render Performance/ useCallback

React Basics~Render Performance/ useCallback

以上就是React Basics~Render Performance/ useCallback的详细内容,更多请关注其它相关文章!