LoginSignup
0
1

More than 3 years have passed since last update.

適当なHooks入門【useEffect後編】

Posted at

概要

Reactで開発するにあたってHooksちゅう新しい機能を使うので、公式ドキュメントで勉強したことを投稿していこうと思います。

公式ドキュメント
前回のあらすじ

以下はライフサイクルの処理をuseEffectを用いて記述した方法です。

ComponentDidMount/componentWillUnmount

useEffect(() => {
    // componentDidMountでしたい処理
    const componentDidMount = () => {
        // 処理
    }
    componentDidMount();

    return () => {
        // componentWillUnmountでしたい処理
    };
}, []);

第二引数に空配列([])を指定することで、副作用とそのクリーンアップを 1 度だけ(マウント時とアンマウント時にのみ)実行されます。
つまりcomponentDidMount と componentWillUnmount による処理をしたい場合は、空の配列 ([]) を渡せば似たような表現が出来ます。

ComponentDidUpdate/setStateのコールバック

const [count, setCount] = useState(0); // countの初期値は『0』

const plus = () => {
    setCount(count++)
}

useEffect(() => {
    // componentDidUpdateでしたい処理
    const componentDidUpdate = () => {
        // 処理
        document.title = count;
    }
    componentDidUpdate();
}, [count]);

return (
    <>
        <div>{ count }</div>
        <button onclick="plus()">+</button>
    </>
)

第二引数にcountを渡すことでsetCountが実行されcountが変更された場合に、処理が実行されます。
つまりcomponentDidUpdate や setStateのコールバックによる処理をしたい場合は、配列内に副作用を起こしたい場合に比較する値(上記の例だと「count」)を渡すことで、countの値が前回のレンダリング前と同一でなければ副作用が実行されます。

ざっくりまとめ

1, componentDidMountをuseEffectで表現したい場合は第二引数に空配列を渡せすんや
2, componentWillUnmountをuseEffectで表現したい場合は副作用内で関数を返すんや
3, ComponentDidUpdateやsetStateのコールバックをuseEffectで表現したい場合は第二引数に副作用を起こしたい場合に比較する値を渡すんや

終わりに

自分なりの解釈ですので、いい方法などありましたら教えていただければ幸いです。

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