Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

React useMemo 钩子


React useMemo 钩子返回一个记忆化的值。

可以将记忆化理解为缓存一个值,以便不需要重新计算。

useMemo 钩子仅在其中一个依赖项更新时运行。

这可以提高性能。

useMemouseCallback 钩子很相似。主要区别在于 useMemo 返回一个记忆化的值,而 useCallback 返回一个记忆化的函数。您可以在 useCallback 章节 中了解更多关于 useCallback 的信息。


性能

useMemo 钩子可用于防止代价高昂、资源密集型函数不必要地运行。

在此示例中,我们有一个在每次渲染时都运行的代价高昂的函数。

更改计数或添加待办事项时,您会注意到执行延迟。

示例

一个性能不佳的函数。 expensiveCalculation 函数在每次渲染时都会运行

import { useState } from "react";
import ReactDOM from "react-dom/client";

const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState([]);
  const calculation = expensiveCalculation(count);

  const increment = () => {
    setCount((c) => c + 1);
  };
  const addTodo = () => {
    setTodos((t) => [...t, "New Todo"]);
  };

  return (
    <div>
      <div>
        <h2>My Todos</h2>
        {todos.map((todo, index) => {
          return <p key={index}>{todo}</p>;
        })}
        <button onClick={addTodo}>Add Todo</button>
      </div>
      <hr />
      <div>
        Count: {count}
        <button onClick={increment}>+</button>
        <h2>Expensive Calculation</h2>
        {calculation}
      </div>
    </div>
  );
};

const expensiveCalculation = (num) => {
  console.log("Calculating...");
  for (let i = 0; i < 1000000000; i++) {
    num += 1;
  }
  return num;
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

运行示例 »


w3schools CERTIFIED . 2022

获取认证!

完成 React 模块,完成练习,参加考试并成为 w3schools 认证人员!!

$95 报名

使用 useMemo

为了解决此性能问题,我们可以使用 useMemo 钩子来记忆化 expensiveCalculation 函数。这将导致该函数仅在需要时运行。

我们可以使用 useMemo 包裹代价高昂的函数调用。

useMemo 钩子接受第二个参数来声明依赖项。代价高昂的函数仅在其依赖项发生更改时运行。

在以下示例中,代价高昂的函数仅在 count 更改时运行,而不是在添加待办事项时运行。

示例

使用 useMemo 钩子的性能示例

import { useState, useMemo } from "react";
import ReactDOM from "react-dom/client";

const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState([]);
  const calculation = useMemo(() => expensiveCalculation(count), [count]);

  const increment = () => {
    setCount((c) => c + 1);
  };
  const addTodo = () => {
    setTodos((t) => [...t, "New Todo"]);
  };

  return (
    <div>
      <div>
        <h2>My Todos</h2>
        {todos.map((todo, index) => {
          return <p key={index}>{todo}</p>;
        })}
        <button onClick={addTodo}>Add Todo</button>
      </div>
      <hr />
      <div>
        Count: {count}
        <button onClick={increment}>+</button>
        <h2>Expensive Calculation</h2>
        {calculation}
      </div>
    </div>
  );
};

const expensiveCalculation = (num) => {
  console.log("Calculating...");
  for (let i = 0; i < 1000000000; i++) {
    num += 1;
  }
  return num;
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

运行示例 »


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.