eng:https://devdocs.io/react/react-api#reactmemo
zh-cn:https://zh-hans.reactjs.org/docs/react-api.html#reactmemo
create a index.js file, then append a child called Swatch
index.js is a React component,
count, colorSwatch receive props includes colorSwatch without memo:| SWATCH HAS SAME PROPS: | click color button 5 times | ReRender App && Re-Render Swatch |
| SWATCH HAS Different PROPS: | click color button 5 times | ReRender App && Re-Render Swatch |
Swatch wrapped in memo:const T = React.memo(Swatch) return <T color={color}></T>复制成功
| SWATCH HAS SAME PROPS: | click count button 5 times | ReRender App Only |
| SWATCH HAS Different PROPS: | click color button 5 times | ReRender App && Re-Render Swatch |
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> */} </> )复制成功
当props中传入对象和方法的时候,memoization会被破坏。
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.

此时有两种解决方法
React.memo提供第二个参数const T = memo(Swatch, (prevProps, nextProps) => { return prevProps.params.color === nextProps.params.color })复制成功

