LoginSignup
220
137

More than 5 years have passed since last update.

[React] Component と PureComponentの違い

Last updated at Posted at 2018-01-16

1. 前書き

React は Component を Update するか決定する過程で、
Component の shouldComponentUpdate を実行し、Update する必要があるか判断する。

Reactは shouldComponentUpdate で
true を返すと Update する必要があると判断し、
false を返すと Update をする必要がないと判断する。

2. PureComponentとは

React PureComponent はデフォルトの shouldComponentUpdate を変更した Component である。
浅い比較(shallow-Equal)によって Update するかしないかを決定する。

  • React.PureComponentのイメージ
class PureComponent extends React.Component {
    shouldComponentUpdate(nextProps, nextState) {
        return !(shallowEqual(this.props, nextProps) && shallowEqual(this.state, nextState));
    }
    
}

本番ソースの該当部分のコード

3. Component と PureComponentのStateやPropsが変更時の比較図

Kobito.BIMUZ8.png

Component と PureComponentの使い分け

(1) 原則

render関数を発火させる回数を減らせば減らせるほど、
Reactの性能を発揮することができる。

(2) 結論

  • propsstateが常に変化していれば、PureComponentを使わず、Componentを使うべし。(理由:shouldComponentUpdate内のshallowEqualも時間かかる)
  • propsstateがあまり変わらなければ、PureComponentを使うべし。
  • propsstateが変わらなければ、どちらでもOK.
  • React自体VirtualDOM機構で差分しかrenderされず性能を保証してくれるため、初心者は気にせずComponentを使用。Bottle Neckになったら、最適化すれば良い。

4. 使用例

TODO

5. 注意点

  • PureComponentを使用する場合、shouldComponentUpdate内の比較が 浅い比較(shallow-Equal) (objectのreferenceしか比較しない)なので、 setState の時は Immutable規則を守らないとrenderされないtrapにはまる。

Immutable(不変)規則とは

既存のStateやPropsを直接修正するのではなく、
新たにobjectを作った上で変更する。

  • 正しい使い方
const props = {
  id: 1,
  list: [1, 2, 3]

}

const nextProps = {
  ...props,
  list: [...props.list, 4]
}
  • 間違った使い方
const props = {
  id: 1,
  list: [1, 2, 3]
}

const list = props.list; // 変更前のpropsと同じreferenceになるため
list.push(4)

nextProps = {
  ...props,
  list
}

6. おまけ

  • React Lifecycle

React Lifecycle

7. 参考

http://mp.weixin.qq.com/s/05SWQW7XeHHsk4QvACiMeA
https://kunigami.blog/2015/04/28/react-js-introduction/
http://jyane.jp/2016/08/12/react-purecomponent.html

220
137
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
220
137