0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactのデータフェッチ用フック useSWR利用方法

Posted at

皆さん、こんにちは。

今回は【Reactのデータフェッチ用フック useSWR利用方法】について紹介させていただきます。

SWRとは?

SWRは「Stale While Revalidate」の略で、表示速度とデータの新鮮さを両立するデータ取得戦略です。

公式サイト:👉 https://swr.vercel.app/

特徴

  • キャッシュ機能で高速描画
  • 自動再取得(再検証)
  • データの共有と同期
  • 軽量・ゼロ設定
  • TypeScript対応

インストール方法

npm install swr

基本的な使い方

import useSWR from 'swr'

// fetcher関数を定義
const fetcher = (url: string) => fetch(url).then(res => res.json())

export default function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)

  if (isLoading) return <div>読み込み中...</div>
  if (error) return <div>エラーが発生しました</div>

  return <div>こんにちは、{data.name}さん!</div>
}

useSWRの返り値

useSWR(key, fetcher) は次のようなオブジェクトを返します:

プロパティ 説明
data APIから取得したデータ
error エラー情報
isLoading ロード中かどうか(SWR v2以降)
mutate データの手動更新関数
isValidating 再フェッチ中かどうか

実用オプションの例

  • フォーカス時に自動再フェッチ
useSWR('/api/user', fetcher, {
  revalidateOnFocus: true
})
  • 一定間隔で自動更新
useSWR('/api/user', fetcher, {
  refreshInterval: 10000 // 10秒ごとに再取得
})
  • 条件付きでフェッチ
const shouldFetch = userId !== null
const { data } = useSWR(shouldFetch ? `/api/user/${userId}` : null, fetcher)

mutateで手動更新

mutate を使えば、データを即座に書き換えることができます。

import useSWR, { mutate } from 'swr'

// 一時的にローカルキャッシュだけ更新(再取得なし)
mutate('/api/user', { name: '太郎' }, false)

// データを再取得する
mutate('/api/user')

SWRとaxiosの組み合わせ

import axios from 'axios'
import useSWR from 'swr'

const fetcher = (url: string) => axios.get(url).then(res => res.data)

const { data } = useSWR('/api/user', fetcher)

SWRとReact Queryの違い(簡易比較)

項目 SWR React Query
学習コスト 低い やや高め
キャッシュ 文字列キーで管理 オブジェクトでもOK
Mutation機能 mutateで簡易対応 useMutationあり
Devtools 公式なし(非公式あり) 公式あり

まとめ

SWRは以下のような用途に特におすすめです:

  • GET中心のアプリ
  • 表示速度重視のSPA
  • 状態管理ライブラリを極力使いたくないとき

軽量・高速・シンプルで、ReactアプリのAPI通信を大幅に快適にしてくれます。

今日は以上です。

ありがとうございました。
よろしくお願いいたします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?