react: useMemo

useMemo 避免组件更新结果重新计算,提高性能
在https://ant.design/components/button-cn 打开codesanbox,替换代码保存

import React, { useMemo, useState, useEffect } from "react";

function MyComponent({ propB = 2 }) {
  const [data, setData] = useState(1);
  const [bool, setBool] = useState(true);
  const expensiveOperation = useMemo(() => {
    console.log("计算结果expensiveOperation");
    return data * propB;
  }, [data, propB]); // 依赖的属性在数组中传入

  useEffect(() => {
    console.log("组件更新了");
  });

  return (
    <>
      <button
        onClick={() => {
          setBool(!bool);
        }}
      >
        更新页面 {bool + ""}
      </button>
      <button
        onClick={() => {
          setData(data + 1);
        }}
      >
        修改
      </button>
      <div>{expensiveOperation}</div>
    </>
  );
}

export default MyComponent;

你可能感兴趣的:(react18,react.js,javascript,前端)