LoginSignup
236
181

More than 5 years have passed since last update.

React Componentのライフサイクルのまとめと利用用途

Posted at

React Componentのライフサイクルのまとめ&利用用途

利用用途については雑です。

マウント時

  • componentWillMount
  • componentDidMount

マウントされるときに1度だけ実行される。以降は実行されない。

void componentWillMount()

render()直前の処理。
ここでthis.setState()を行うと、render()は更新されたstateを参照する。

void componentDidMount()

実際のDOMが存在するので、DOM触り放題。
this.setState()はできる。

更新時

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • componentDidUpdate

void componentWillReceiveProps(object nextProps)

新しいpropsを受け取ると実行される。
propsによってstateを変更する場合はここでthis.setState()を行う。
更新時ライフサイクル内でthis.setState()を使える場所はここだけ。
この関数内のthis.setState()がさらなるrender()を呼ぶことはない。

boolean shouldComponentUpdate(object nextProps, object nextState)

パフォーマンス・チューニング時に触る。
returnでbool値を返さなければならない。
falseを返すと、以降のcomponentWillUpdate(), render(), componentDidMount()の処理がスキップされる。
this.setState()は呼んではいけない。呼ぶと無限ループに入り、スタックを食いつぶして止まる。

void componentWillUpdate(object nextProps, object nextState)

render()前に何か準備する。
this.setState()は呼んではいけない。
componentWillUpdate()render()の間のタイミングでthis.props, this.stateで参照できる値が更新される。

void componentDidUpdate(object prevProps, object prevState)

新しいDOM触り放題。
this.setState()は呼んではいけない。

アンマウント時

void componentWillUnmount()

後始末を書くところ。

備考

以下のリンクのライフサイクルの図を合わせて見ると理解が捗ると思います。
React component ライフサイクル図

236
181
1

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
236
181