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
What's in a price? How to price your products and services
michaelherold
247
13k
Why Mistakes Are the Best Teachers: Turning Failure into a Pathway for Growth
auna
0
51
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
35
3.4k
The SEO Collaboration Effect
kristinabergwall1
0
350
ラッコキーワード サービス紹介資料
rakko
1
2.3M
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
31
9.9k
Chasing Engaging Ingredients in Design
codingconduct
0
110
DBのスキルで生き残る技術 - AI時代におけるテーブル設計の勘所
soudai
PRO
62
49k
Ethics towards AI in product and experience design
skipperchong
2
190
Unlocking the hidden potential of vector embeddings in international SEO
frankvandijk
0
170
A Tale of Four Properties
chriscoyier
162
24k
Technical Leadership for Architectural Decision Making
baasie
1
240
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 変換 手動 自動 機能性 自前で色々書く 豊富な設定 シチュエーション 小規模 中~ 大規模