Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
useSWRについて
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
魔迦論
May 01, 2025
0
10
useSWRについて
useSWRとは
(番外編)useEffectでデータ取得?
魔迦論
May 01, 2025
Tweet
Share
More Decks by 魔迦論
See All by 魔迦論
GitHub Actionsのハンズオン
mackalong
0
35
英文の読み方
mackalong
0
13
OpenAPIについて
mackalong
0
20
JWTについて_基本編
mackalong
1
15
Featured
See All Featured
Learning to Love Humans: Emotional Interface Design
aarron
275
41k
Mozcon NYC 2025: Stop Losing SEO Traffic
samtorres
0
140
Game over? The fight for quality and originality in the time of robots
wayneb77
1
110
Data-driven link building: lessons from a $708K investment (BrightonSEO talk)
szymonslowik
1
910
Hiding What from Whom? A Critical Review of the History of Programming languages for Music
tomoyanonymous
2
410
Thoughts on Productivity
jonyablonski
74
5k
A Soul's Torment
seathinner
5
2.2k
The Director’s Chair: Orchestrating AI for Truly Effective Learning
tmiket
1
96
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
128
55k
SEO in 2025: How to Prepare for the Future of Search
ipullrank
3
3.3k
Ruling the World: When Life Gets Gamed
codingconduct
0
140
A Tale of Four Properties
chriscoyier
162
24k
Transcript
useSWR について
useSWR とはなにか 概念 API からのデータ取得を手助けするReactHooks ライブラリ SWR : Stale-While-Revalidate (古い情報を先に見せて、裏で更新する戦略)
やってること 1. Stale : キャッシュから古いデータ取得& 表示 2. While : その間に( 非同期) 、最新データ取得& 表示 3. Revalidate : 取得した最新データをキャッシュに書き込む
実体( 基本的な使い方) //まずはfetcher(中身はaxios または fetch) const fetcher = (url: string)
=> axios.get(url).then(res => res.data); export default function Profile() { //宛先urlと作ったfetcherを引数で渡す const { data, error, isLoading } = useSWR('/api/user', fetcher); //データ取得できるまではisLoadingがtrue if (isLoading) return <div>読み込み中...</div>; if (error) return <div>エラーが発生しました</div>; return <div>こんにちは、{data.name}さん!</div>; }
何が良いのか 可読性が高い ⇨useEffect などを使うより読みやすい( 後述) 先述したキャッシュ戦略 ⇨UX の向上 ⇨UI を待たせないという非同期処理の強みをより強固にする
( 番外)useEffect でデータ取得? useEffect でのデータ取得については賛否両論ある(?) → それについては理解が深まったら更新予定 ただ、useEffect を単なるデータ取得に使うのはコスパ悪い印象 →
エラーハンドリングなどを自前で実装する必要あり(?) → コードが複雑になる ⇨可読性が低くなる ⇨意図しない再レンダリング せっかくデータ取得に特化したuseSWR があるなら そっち使ったほうが良い
( 番外)fetch とaxios について どちらも非同期のAPI リクエスト処理を行うモジュール 比較項目 fetch axios 標準かどうか
標準 外部 レスポンスのJSON 変換 手動 自動 機能性 自前で色々書く 豊富な設定 シチュエーション 小規模 中~ 大規模