4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【React Hooks】 useEffectの動作タイミングをきっちり理解する

Posted at

useEffectとは

  • React Hooksにおいてライフサイクルメソッドを関数コンポーネントで実現する仕組み。
  • classコンポーネントで言うcomponentDidMountなどに相当する。
  • 1つの関数コンポーネントに複数記述しても良い。

サンプルコード

以下のサンプルコードを用いて解説したい。

import React, { useEffect, useState} from 'react';
import './App.css';

const App = props => {
  const [state, setState] = useState(props)
  const { id, name } = state

  useEffect(() => {
    console.log('#001:レンダリング毎に呼ばれる')
  })

  useEffect(() => {
    return () => console.log('#002:アンマウント直前に呼ばれる')
  })
  
  useEffect(() => {
    console.log('#003:マウント時とアンマウント時にのみ呼ばれる')
  },  [])

  useEffect(() => {
    console.log('#004:特定のstateが変更された場合のみ呼ばれる')
  },  [name])

  return (
    <>
      <p>id:{id} name:{name}</p>
      <p>id:<input value={id} onChange={e => setState({...state, id: e.target.value})} /></p>
      <p>name:<input value={name} onChange={e => setState({...state, name: e.target.value})} /></p>
    </>
  )
}

App.defaultProps = {
  id: 'Id001',
  name: 'NoName'
}

レンダリング時

以下のように記述するとrenderメソッドが走る度に処理が呼ばれる。初回のレンダリング時はもちろんであるが、stateやpropsが更新された際にも呼ばれることとなる。

 useEffect(() => {
    console.log('#001:レンダリング毎に呼ばれる')
  })

アンマウント時

useEffect内で関数をリターンさせるとアンマウント時の処理を記述できる。

  useEffect(() => {
    return () => console.log('#002:アンマウント直前に呼ばれる')
  })

マウント時およびアンマウント時

空配列[]を第2引数に指定するとマウント・アンマウントに限定させることができる(001のように更新時には呼ばれなくなる。)

  useEffect(() => {
    console.log('#003:マウント時とアンマウント時にのみ呼ばれる')
  },  [])

特定のstateが更新された時

特定の値が更新された場合に限定したい場合は、第2引数の配列に変数名を記載すれば良い。下記の例ではnameが更新された時(nameを保持するinputのonChangeが呼ばれた時)にのみ実行される。

  useEffect(() => {
    console.log('#004:特定のstateが変更された場合のみ呼ばれる')
  },  [name])
4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?