React.memo

原作视频

是否建立memoization的对比

what is React.memo

eng:https://devdocs.io/react/react-api#reactmemo

zh-cn:https://zh-hans.reactjs.org/docs/react-api.html#reactmemo

  1. create a index.js file, then append a child called Swatch

  2. index.js is a React component,

  • it has states: count, color
  • two buttons can control its states and Re-Render App
  • Swatch receive props includes color
  1. Swatch without memo:
SWATCH HAS SAME PROPS:click color button 5 timesReRender App && Re-Render Swatch
SWATCH HAS Different PROPS:click color button 5 timesReRender App && Re-Render Swatch
  1. Swatch wrapped in memo:
 const T = React.memo(Swatch)
 return <T color={color}></T>
复制成功
1
2
SWATCH HAS SAME PROPS:click count button 5 timesReRender App Only
SWATCH HAS Different PROPS:click color button 5 timesReRender App && Re-Render Swatch

code

import React, { useEffect, useState, memo } from 'react'
import Swatch from './Swatch'
const T = memo(Swatch)
export default function ComponentWithMemo() {
    const [count, setCount] = useState(0)
    const [color, setColor] = useState('red')

    console.log(`App rendered: ${count}`)
    const countAppRendered = () => setCount(count + 1)

    useEffect(() => {
        return () => {
            setCount(0)
            setColor('red')
        }
    }, [])
    return (
        <>
            <h1>{count}</h1>
            <div>
                <button style={{ margin: 5 }} onClick={countAppRendered}>Re-Render App</button>
                <button onClick={() => {
                    countAppRendered()
                    setColor(color === 'red' ? 'blue' : 'red')
                }}>Change Color</button>
            </div>
            <T color={color}></T>
            {/* <Swatch color={color}></Swatch> */}
        </>
    )
复制成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

破坏React.memo

当props中传入对象和方法的时候,memoization会被破坏。

  1. 如果props中只有对象:

everytime we go through here and we create a new object with a new reference.

it may have exactly the same value,

but react is doing a shallow comparison on the props.

image-20220404225836511

此时有两种解决方法

  • React.memo提供第二个参数
const T = memo(Swatch, (prevProps, nextProps) => {
	return prevProps.params.color === nextProps.params.color
})
复制成功
1
2
3
  • 将这个对象用useMemo声明
image-20220404232816452
  1. 如果props中你还定了个方法,也会破坏memoization
image-20220404233134236

diff code

links:open in new window

晓露寝安浅云逍遥十漾轻拟