SlideShare a Scribd company logo
1 of 24
Download to read offline
ライフサイクルを意識しながら
Reactコードを書こう
koralle and 2021/08/20
Author: koralle
Web Developer (2nd)
Tech
TypeScript/React
Python
Swift
GCP
Qiita
GitHub
Zenn
ライフサイクルって何????
ライフサイクル(生活環)
生活環(せいかつかん、Biological life cycle)、ライフサイクル(Life cycle)とは、生物の成長、生殖に伴う変化がひ
と回りする間の様子、特に核相との関わりから見た場合のそれを指す言葉である。生活環- Wikipedia
引用:https://rika-net.com/contents/cp0520b/contents/c1ferm.html
Reactコンポーネントのライフサイクル(1/2)
この図についてはReact公式ドキュメントに以下の記述があります。
このライフサイクル図をチートシートとして使用できます。
引用:https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
Reactコンポーネントのライフサイクル(2/2)
Reactコンポーネントにおけるライフサイクルとは「コンポーネントがマウントされる」〜「マウント解除される」まで
の一連のプロセスであることが分かる。
React.Componentを継承するクラスコンポーネントまたはReact.FC(React.VFC)型の関数コンポーネントのインスタン
スが作成され、DOMツリーに挿入されること
インスタンスがDOMツリーから削除されること

このアンマウント操作によりインスタンスの作成時に確保したメモリが解放される
マウント
マウント解除(=アンマウント)
ここではライフサイクルメソッドの詳細な説明はしない
既に記事が多く存在するからLTっぽくない
詳細に説明していたら時間内に収まらない
このあとは非常にやりがちなミスをライフサイクルの視点から考察することにします。
この後の話の前提
登場するコンポーネントは全部関数コンポーネント
json-server でモックサーバー( http://localhost:4406 )を立てる
レスポンスの型定義もこんな感じで。
` ` ` `
1 {

2 "user": {

3 "id": 4649,

4 "email": "hogehoge@example.com",

5 "name": "React Taro"

6 }

7 }
1 type User = {

2 id: number;

3 email: string;

4 name: string;

5 }
ついやりがちなミス
下のコンポーネントをブラウザに描画しようとすると失敗します。
1 import React, { useEffect, useState, VFC } from 'react'

2
3 // User型の型定義を省略

4
5 const App: VFC = () => {

6 const [user, setUser] = useState<User>();

7
8 useEffect(() => {

9 fetch('http://localhost:4406/user')

10 .then((res) => res.json())

11 .then((json) => {

12 setUser(json)

13 })

14 }, []);

15
16 return <>

17 <p>{user.id}</p>

18 <p>{user.name}</p>

19 <p>{user.email}</p>

20 </>;

21 }

22
23 export default App;
エラー内容
なぜ起きた???
直接的な原因はstateである user が undefined の時にuserのプロパティを参照しているからなんだけど…
なぜ user が undefined になるなんだろう???
` ` ` `
` ` ` `
useEffectフックの中で user をnon-undefinedな値に更新しているから。
` `
useEffectフックは「副作用」に該当する処理を実行する
Reactにおける副作用とは(公式ドキュメントより)
データの取得、購読(subscription) の設定、あるいはReact コンポーネント内のDOM の手動での変更、といったもの
はすべて副作用の例です。
また副作用の実行タイミングについてこうある
典型的には、副作用はReact がDOM を更新したあとに起こすようにしたいのです。
useEffectについてはこうある
useEffect は何をやっているのか?このフックを使うことで、レンダー後に何かの処理をしないといけない、というこ
とをReact に伝えます。

React はあなたが渡した関数を覚えており(これを「副作用(関数)」と呼ぶこととします)、DOM の更新の後にそ
れを呼び出します。
一度ライフサイクルの図を見返す
副作用はDOMの更新、つまり画面にコンポーネントを描画した後に実行される
逆に言えば、useEffectによる副作用の実行前にコンポーネントは少なくとも一度描画されている
そのため、副作用の実行前のコンポーネントの振る舞いを考慮する必要がある
今回のケースでは…
実は副作用の実行前にuserのidプロパティにアクセスしていた
書き直す(その1)
条件分岐で user の値をチェックする

user がFalsyならローディング中とみなしている
` `
` `
1 import React, { useEffect, useState, VFC } from 'react'

2
3 // User型の型定義を省略

4
5 const App: VFC = () => {

6
7 const [user, setUser] = useState<User>();

8
9 // useEffectを省略

10
11 if (!user) return <p>Loading...</p> // これ

12
13 return <>

14 <p>{user.id}</p>

15 <p>{user.name}</p>

16 <p>{user.email}</p>

17 </>;

18 }

19
20 export default App;
書き直す(その2)
&& 演算子を賢く使う
` `
1 import React, { useEffect, useState, VFC } from 'react'

2
3 // User型の型定義を省略

4
5 const App: VFC = () => {

6
7 const [user, setUser] = useState<User>();

8
9 // useEffectを省略

10
11 // これ

12 return <>

13 {

14 user &&

15 <>

16 <p>{user.id}</p>

17 <p>{user.name}</p>

18 <p>{user.email}</p>

19 </>

20 }

21 </>;

22 }

23
24 export default App;

25
余談だけど…
同じエラーログが2回表示されているのが違和感ありませんか?
strictモード
Reactアプリの欠陥を検出する仕組み
開発ビルドにのみ適用される
1 import React from 'react'

2 import ReactDOM from 'react-dom'

3 import App from './App'

4
5 ReactDOM.render(

6 <React.StrictMode> // これ

7 <App />

8 </React.StrictMode>, // これ

9 document.getElementById('root')

10 )
strictモードでは一部のライフサイクルメソッドを意図的に2回呼び出す
公式ドキュメントにはこうある
strict モードでは自動的には副作用を見つけてはくれませんが、
それらの副作用をほんの少し決定的にすることによって特定できる助けになります。

これは、以下の関数を意図的に2 回呼び出すことによって行われます。
クラスコンポーネントのconstructor, render, shouldComponentUpdate メソッド
クラスコンポーネントのgetDerivedStateFromProps 静的メソッド
関数コンポーネントの本体
state 更新用関数(setState の第1 引数として渡されるもの)
useState, useMemo, useReducer に渡される関数
実はReact v17以降ではこんな仕様がある
React 17 以降で、React はconsole.log() のようなコンソールメソッドを自動的に変更し、ライフサイクル関数の2 回
目のコールでログが表示されないようにします。これにより特定のケースで意図しない動作を引き起こすことがありま
すが、回避策も存在します。
おそらく多分こういうことでは
まとめ
Reactコンポーネントにおけるライフサイクルとは「コンポーネントがマウントされる」〜「マウント解除
される」までの一連のプロセス
副作用を含むコンポーネントを作るときはライフサイクルを意識しよう
今回の内容に直接関係ないですが…
Vite
React.js (v17系)
TypeScript
Slidev
Docker + Remote Container
サンプルコードの構成、開発環境
スライド作成
その他
参考: ライフサイクルメソッド
ライフサイクルメソッドがわかればReactの50%は理解したと言えなくもない- Qiita
React(v16.4) コンポーネントライフサイクルメソッドまとめ- Qiita
Reactの基礎【ライフサイクル】
【Reactの設計を学ぶ】ライフサイクルを知ろう| CodeShip blog

More Related Content

Featured

Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 

ライフサイクルを意識しながらReactコードを書こう