【React】Lifecycleについて
Lifecycleとは
React Componentの生成、更新、破棄に関わる一連のイベントのことを指します。
Class Lifecycle
Classコンポーネント時代のReactのLifecycleには、3つのフェーズがあります
Mounting
コンポーネントのインスタンスが作成され、DOMに挿入される段階. つまり、React ComponentがHTMLタグとして、ターゲットとなるHTMLの要素に挿入され、ブラウザの画面上に表示されます。
Updating
コンポーネントの状態が更新され、再レンダーされる段階
Unmounting
コンポーネントがDOMから削除される段階
Mounting
4つの処理が呼び出されます。
- constructor()
- static getDerivedStateFromProps()
- render()
- componentDidMount()
constructor()
React Componentsのコンストラクタが呼び出され、初期化を行います。初期化では、オブジェクトのデフォルト値の設定や、引数の型のチェック, 初期値からstateオブジェクトの作成が実行されます。
static getDerivedStateFromProps()
こちらの関数では、初期値にpropsの値を利用し、ユーザーの操作に応じでstateの値を変更する場合に使用します。次のような場合です。
static getDerivedStateFromProps(nextProps: Props, prevState: State) {
const name = nextProps.name.toUpperCase();
if (prevState.name !== name) {
return { isDerivered: true, name };
}
return;
}
render()
propsやstateの値を調べ、JSX経由で作成されたReact Componentを返します。
componentDidMount()
React ComponentがDOMに追加された後(マウント後)、一度だけ呼び出されます。DOMにアクセスする必要がある処理や、HTTP Requestの送信やsetInterval()の実行の処理を扱います。useEffect
に空配列を渡した時と同じように動作します。
componentDidMount() {
console.log("Hello");
}
Updating
こちらの5つの処理が呼び出されます。
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
shouldComponentUpdate()
getSnapshotBeforeUpdate()
componentDidUpdate()
再レンダリングされた後に呼び出されます。基本的には、更新前の値と更新後の値を比較して何か処理を行います。そのため、もし特定のstateに関してのみ動作させたい場合には指定する必要があります。
componentDidUpdate(prevProps, prevState)
Unmounting
こちらの関数が呼ばれます。
- componentWillUnmount()
componentWillUnmount(
コンポーネントがDOMから削除される直前に呼び出されます。ここには、コンポーネントのリソースを解放したりしてメモリリークを防ぐために必要なクリーンアップ処理を記述します。例えばタイマーをクリアしたり、ストリームやソケットを閉じたりします。useEffect
におけるreturnでこの処理を記述することができます。
useEffect(() => {
window.addEventListener("resize", this.handleResize);
return () => {
// componentwillunmount in functional component.
// Anything in here is fired on component unmount.
window.removeEventListener("resize", this.handleResize);
}
}, [])
Discussion