React.memo Higher Order Components

1. Concept
React.memo is a high-level component. If your component renders the same result with the same props, you can wrap it in React.memo to improve the performance of the component by remembering the rendering result of the component. This means that in this case, React will skip rendering the component and directly reuse the result of the most recent render.

Similar to PureComponent in class components, they are all shallow comparisons, only comparing the data of the first layer.

import React, {
    
     useState, useEffect, useContext } from 'react';

// 如果num不改变当前组件不会重新渲染
const MyComponent =  React.memo((props) => {
    
    
  /* 使用 props 渲染 */
  return (
    <div>{
    
    props.num}</div>
  )
})
export default function hook() {
    
    

  const [num, setNum] = useState(1)

  return (
    <div>
      <button onClick={
    
    () => setNum(num + 1)}>+1</button>
      <MyComponent num={
    
    num}></MyComponent>
    </div>
  )
}

2. Features
React.memo only checks props changes. If a function component is wrapped by React.memo and its implementation has a useState, useReducer or useContext Hook, it will still re-render when the state or context changes.

3. The second parameter is acceptable

By default, it will only do shallow comparison of complex objects, that is, only compare the keys of the first layer. shallowEqual is mainly compared through Object.js, so for objects or arrays, it is false, so it will be rendered every time. If you want to control the comparison process, then please pass in a custom comparison function to achieve it through the second parameter. The second parameter is a function that returns true and does not render, and false renders

import React, {
    
     useState, useEffect, useContext } from 'react';


const MyComponent =  React.memo((props) => {
    
    
  /* 使用 props 渲染 */
  return (
    <div>{
    
    props.num}</div>
  )
  /**
   * prevProps 上次的值
   * nextProps 最新的值
   * 
   * 如果传来的值是偶数的话则不更新组件
   */
}, (prevProps, nextProps) => {
    
    
  console.log(nextProps, nextProps.num % 2)
  return nextProps.num % 2 === 0
})

export default function hook() {
    
    

  const [num, setNum] = useState(1)

  useEffect(() => {
    
    
    /**
     * 当它是一个空数组时,回调只会被触发一次,类似于 componentDidMount
     */
    console.log("componentDidmount")
  }, [])

  return (
    <div>
      <button onClick={
    
    () => setNum(num + 1)}>+1</button>
      <MyComponent num={
    
    num}></MyComponent>
    </div>
  )
}

Guess you like

Origin blog.csdn.net/qq_42931285/article/details/131886196