LoginSignup
1
0

More than 3 years have passed since last update.

ReactHooks useEffectを "超" 簡潔に説明

Posted at

useEffectを勉強していて色々と混乱したので、超簡潔にまとめてみました。

index.js
const App = (props) => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>The current count is {count}</p>
      <button onClick={() => setCount( count -1)}>-1</button>
      <button onClick={() => setCount(0)}>reset</button>
      <button onClick={() => setCount(count + 1 )}>+1</button>
    </div>
  )
}

ReactDOM.render(<App />,document.getElementById('root');

変数countには初期値で0が指定されており、-1ボタンを押すとマイナス1、+1ボタンを押すとプラス1づつ増えていく。また、resetボタンを押すと0に戻るという仕組みのカウント機能を元に説明します。

第二引数に何も書かない場合 (componentDidmount / ComponentDidUpdate)

index.js
  useEffect(() => {
     console.log('useEffect ran');
  })

つまり、「一番最初のレンダリング時」と「あらゆるコンポーネントのstateやpropsの値に変更がある時」に実行される。

第二引数に[]がつく場合 (componentDidMount)

index.js
  useEffect(()=>{
    console.log('This should only run once')
  }, [])

「一番最初のレンダリング時」にのみ実行される

第二引数に値を指定した場合 (componentDidmount / ComponentDidUpdate)

index.js
  useEffect(() => {
     console.log('useEffect ran');
  },[count])

「一番最初のレンダリング時」と「ある特定のstateもしくはprops(ここではcount)の値が変更した時」に実行される
実行されるタイミングは「第二引数に何も書かない場合」と似ているが、具体的な値を第二引数に指定してあげることで限定できる。

1
0
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
1
0