[note] React Performance
Pure Component
- React.PureComponent @ react.js
- shallow-compare @ react.js
- shouldComponentUpdate in action @ react.js > performance
Pure Component 的意思和 Pure Function 類似,當某個 component 只要有相同的 input(state 和 props)時,就會回傳相同內容時,即稱作 Pure Component。
當我們確定某個 React 元件符合 Pure Component 的情況時,就可以讓該元件繼承 React.PureComponent
而不是 React.Component
,PureComponent 比起一般的 Component 幫忙實作了 shouldComponentUpdate
的方法,它會透過 shallow-compare 的方式 state 和 props 有無差異後來決定要不要更新該 component。
React.memo
React.memo @ react.js
當 React 元件在有相同的 props 就會 render 相同的內容時,可以透過 React.memo()
來提升效能。
React.memo()
只會檢查 props 的差異,如果你在該元件中有使用到 useState
, useReducer
或 useContext
的話,當 state 或 context 有改變時,這個元件依然會重新渲染。
和 React.PureComponent 一樣,React.memo 也是使用 shallow compare 的方式在比對物件是否相同。
Compare Algorithm in React
shallow-compare
- shallow-compare @ react.js
- shallowEqual.js @ react > packages > shared
實際上,shallowCompare
底層是用 shallowEqual
的方式在進行比對,而 shallowEqual
這個方法會(其程式碼可以參考這個 gist):
- 針對 native types 先用
Object.is
對兩個值做判斷,如果是true
就回傳 - 再比較是否是相同的物件(只會比到第一層)或陣列
// native type
shallowEqual('foo', 'foo'); // true
// object
shallowEqual({ foo: 'foo' }, { foo: 'foo' }); // true
shallowEqual({ foo: { bar: 'bar' } }, { foo: { bar: 'bar' } }); // false
// array
shallowEqual(['foo'], ['foo']); // true
shallowEqual(['foo'], ['foo', 'bar']); // false
Object.is
- objectIs.js @ react > packages > shared
- Object.is @ MDN
Object.is()
可以用來比較兩個值是否相同。Object.is()
和 ===
的差別只有在判斷 +0
、-0
和 NaNs
是會有不同:
Object.is(0, -0); // false
Object.is(+0, -0); // false
0 === -0; // true
Object.is(NaN, 0 / 0); // true
NaN === 0 / 0; // false
Object.is(NaN, Number.NaN); // true
NaN === Number.NaN; // false