Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
useSWRについて
Search
魔迦論
May 01, 2025
21
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
useSWRについて
useSWRとは
(番外編)useEffectでデータ取得?
魔迦論
May 01, 2025
More Decks by 魔迦論
See All by 魔迦論
GitHub Actionsのハンズオン
mackalong
0
46
英文の読み方
mackalong
0
34
OpenAPIについて
mackalong
0
34
JWTについて_基本編
mackalong
1
33
Featured
See All Featured
Bridging the Design Gap: How Collaborative Modelling removes blockers to flow between stakeholders and teams @FastFlow conf
baasie
0
730
The Illustrated Guide to Node.js - THAT Conference 2024
reverentgeek
1
580
Product Roadmaps are Hard
iamctodd
55
13k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
56
3.5k
SEO for Brand Visibility & Recognition
aleyda
0
4.8k
jQuery: Nuts, Bolts and Bling
dougneiner
66
8.6k
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
3
280
VelocityConf: Rendering Performance Case Studies
addyosmani
331
25k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4.6k
Stewardship and Sustainability of Urban and Community Forests
pwiseman
0
560
Fashionably flexible responsive web design (full day workshop)
malarkey
409
67k
Fantastic passwords and where to find them - at NoRuKo
philnash
53
4k
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 変換 手動 自動 機能性 自前で色々書く 豊富な設定 シチュエーション 小規模 中~ 大規模