zoukankan      html  css  js  c++  java
  • [React] useMemo and React.memo

    As a beginner of React, might have the confuses with 'useMemo' and 'React.memo':

    'useMemo': 

    When using functional components in React we may run into situations where we are performing expensive calculations multiple times, even though the values passed in to the functional component hasn't changed.

    This is where useMemo hook comes in. In this lesson we are going to learn how to use useMemo hook to optimize an expensive (in this example - highly expensive operation of adding two numbers together, for simplicity) operation so that its result is recalculated only when it's necessary - that is, when the input arguments have changed. Otherwise, we are going to use an optimized, memoized result.

    'useMemo' is a high order function, which is used to improve expansive operations. It memos the input of function, if inputs are the same, then it won't run the function, but return the memo one:

    import React, { Component, useMemo } from "react";
    
    const expensiveOperation = (first, second) => {
      console.log("Whoah, that's expensive");
      return first + second;
    };
    
    const ExpensiveComponent = ({ first, second }) => {
      const optimized = useMemo(() => expensiveOperation(first, second), [second]);
      return <div>Sum: {optimized}</div>;
    };

    'React.memo':

    Class components can bail out from rendering when their input props are the same using PureComponent or shouldComponentUpdate. Since React 16.6 you can do the same with function components by wrapping them in React.memo.

    'React.memo' is a High order component, which prevent component get rerender if props doesn't change.

    import React, { Component, memo } from "react";
    
    const Header = memo(({ text }) => {
      console.log("render");
      return <div>{text}</div>;
    });
  • 相关阅读:
    [YTU]_2637(编程题:类---矩形类)
    [YTU]_2625( 构造函数和析构函数)
    [YTU]_2498 (C++类实现最大数的输出)
    [YTU]_2433( C++习题 对象数组求最大值)
    [YTU]_2432( C++习题 对象数组输入与输出)
    AC自动机模板1
    trie字典树
    KMP模板
    Count(广工14届竞赛)
    zyb的面试(广工14届比赛)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12845314.html
Copyright © 2011-2022 走看看