正常寫一個範例
import React, {useState} from 'react';
const Test1 = () => {
console.log('Test1')
return(
<div>Test1</div>
);
}
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<Test1 />
<button onClick={(e) => { setCount( count+1 ) }}>ADD</button>
<p>count:{count}</p>
</div>
)
}
點擊ADD 會發現console.log會一直被觸發。
加入memo 後
import React, {useState} from 'react';
const Test1 = (props) => {
console.log('Test1')
return(
<div>Test1</div>
);
}
const Test2 = React.memo(Test1);
export default function App(props) {
const [count, setCount] = useState(0);
return (
<div>
<Test2 />
<p>count:{count}</p>
<button onClick={(e) => { setCount( count+1 ) }}>ADD</button>
</div>
)
}
const MyComponent = React.memo(function MyComponent(props) {
/* render using props */
});
官方文件
React.memo is a higher order component.
If your component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.
React.memo only checks for prop changes. If your function component wrapped in React.memo has a useState or useContext Hook in its implementation, it will still rerender when state or context change.
By default it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.
他說memo是一個進階的語法,memo是透過記憶的方式將效能優化
memo 是一個很好用的語法,但它不能用在class裡面,只能用在函數組件