axios-hooks、react-query(現在は @tanstack/react-query)、swr は、React アプリケーションにおけるサーバー状態の管理とデータフェッチングを簡素化するためのライブラリです。axios-hooks は Axios をフックとしてラップすることに特化しており、既存の Axios 環境との親和性が高いです。react-query は強力なキャッシュ機能とバックグラウンド更新を提供し、複雑なサーバー状態の管理に適しています。swr は Vercel によって開発され、軽量でシンプルな API を特徴とし、特に Next.js との相性が良い設計になっています。
React におけるデータフェッチングは、コンポーネントのライフサイクルと非同期処理をどう統合するかという課題です。axios-hooks、react-query、swr はそれぞれ異なるアプローチでこの問題を解決します。ここでは、実装の詳細、キャッシュ戦略、そして保守性の観点から技術的な比較を行います。
各ライブラリは、データ取得の状態をコンポーネントに提供するフックを提供していますが、その API デザインには明確な違いがあります。
axios-hooks は Axios のインスタンスを直接使用することを前提としています。
loading、error、data、response などのオブジェクトです。// axios-hooks: Axios 設定をそのまま使用
import useAxios from 'axios-hooks';
function UserProfile() {
const { data, loading, error } = useAxios('https://api.example.com/users/1');
if (loading) return <p>読み込み中...</p>;
return <div>{data.name}</div>;
}
react-query はクエリキーを用いてキャッシュを識別します。
// react-query: クエリキーとフェッチ関数
import { useQuery } from '@tanstack/react-query';
function UserProfile() {
const { data, isLoading, error } = useQuery(['user', 1], () =>
fetch('https://api.example.com/users/1').then(res => res.json())
);
if (isLoading) return <p>読み込み中...</p>;
return <div>{data.name}</div>;
}
swr はキーとフェッチ関数のペアをシンプルに扱います。
useSWR フックはキーとフェッチ関数の 2 引数を取ります。// swr: キーとフェッチ関数のペア
import useSWR from 'swr';
function UserProfile() {
const { data, error, isLoading } = useSWR(
'https://api.example.com/users/1',
(url) => fetch(url).then(res => res.json())
);
if (isLoading) return <p>読み込み中...</p>;
return <div>{data.name}</div>;
}
サーバーデータのキャッシュ戦略は、ユーザー体験とサーバー負荷に直結します。
axios-hooks はデフォルトではリクエストごとに通信を行います。
// axios-hooks: 手動での再フェッチ制御
const { data, refetch } = useAxios('https://api.example.com/data');
// ボタンクリックなどで明示的に refetch() を呼ぶ必要がある
<button onClick={refetch}>更新</button>
react-query はウィンドウフォーカスやネットワーク再接続時に自動で再検証します。
staleTime でデータの鮮度を細かく制御できます。// react-query: 自動再検証と staleTime
useQuery(['todos'], fetchTodos, {
staleTime: 1000 * 60, // 1 分間は新鮮とみなす
refetchOnWindowFocus: true // フォーカス時に再検証
});
swr は stale-while-revalidate 戦略をコアに据えています。
// swr: 自動リバリデーション
useSWR('/api/todos', fetcher, {
revalidateOnFocus: true,
dedupingInterval: 2000 // 2 秒以内の重複リクエストを防ぐ
});
POST、PUT、DELETE などのデータ更新処理においても、各ライブラリの設計思想が現れます。
axios-hooks は更新処理用の専用フックを提供していません。
useAxios を使って手動でトリガーする必要があります。// axios-hooks: 手動での更新処理
const [{ loading }, updateUser] = useAxios({
url: '/api/user',
method: 'PUT',
data: { name: 'New Name' }
}, { manual: true });
// 手動で実行関数を呼ぶ
<button onClick={() => updateUser()}>保存</button>
react-query は useMutation フックを提供します。
// react-query: useMutation による管理
const mutation = useMutation(updateUser, {
onSuccess: () => {
queryClient.invalidateQueries(['user']); // 関連キャッシュを無効化
}
});
<button onClick={() => mutation.mutate({ id: 1 })}>保存</button>
swr は useSWRMutation (または独自実装)で対応します。
react-query ほど多機能ではありません。// swr: useSWRMutation (addon)
import useSWRMutation from 'swr/mutation';
const { trigger } = useSWRMutation('/api/user', sendRequest);
<button onClick={() => trigger({ name: 'New Name' })}>保存</button>
ライブラリの将来性とメンテナンス状況は、長期プロジェクトにおいて重要です。
axios-hooks は Axios エコシステムに依存します。
react-query は TanStack 傘下に移行しました。
react-query は v3 で終了し、現在は @tanstack/react-query が公式です。swr は Vercel によってメンテナンスされています。
| 機能 | axios-hooks | react-query | swr |
|---|---|---|---|
| 主な用途 | Axios リクエスト管理 | 複雑なサーバー状態 | 軽量キャッシュ |
| キャッシュ | 最小限 | 高度な制御可能 | 自動(SWR 戦略) |
| ミューテーション | 手動トリガー | useMutation 専用 | useSWRMutation |
| 依存関係 | Axios 必須 | 任意のフェッチ | 任意のフェッチ |
| 保守状況 | 維持中 | 活発(TanStack) | 活発(Vercel) |
axios-hooks は、Axios 依存のレガシーコードを整理したい場合や、キャッシュ機能よりもリクエストの簡素化を優先する場合に有効です。ただし、現代的なデータフェッチングの要件(キャッシュ、再検証など)を満たすには追加の工夫が必要です。
react-query (@tanstack/react-query)は、機能性と拡張性が最優先される場合に最適です。大規模なアプリケーションでサーバー状態を厳密に管理したいなら、これが標準的な選択になります。
swr は、シンプルさとパフォーマンスのバランスを重視する場合に適しています。特に Next.js を使用している場合、摩擦なく導入できるでしょう。
最終的には、チームの技術スタックと、アプリケーションが求めるデータの鮮度管理の複雑さによって決定すべきです。
軽量なフックを好む場合や、Next.js などの Vercel エコシステム上で開発を行う場合に適しています。設定を最小限に抑えつつ、stale-while-revalidate 戦略による基本的なキャッシュと再検証機能をすぐに導入したいプロジェクトで選定されます。
複雑なサーバー状態の管理、高度なキャッシュ制御、ミューテーション(データ更新)の最適化が必要な大規模アプリケーションに適しています。現在は @tanstack/react-query としてメンテナンスされており、エコシステムが最も充実しているため、長期的な保守性を重視するプロジェクトで推奨されます。
既存のプロジェクトで Axios をすでに多用しており、新しいキャッシュ層を導入せずにリクエスト状態(ローディング、エラー、データ)だけをフックで管理したい場合に適しています。大規模なキャッシュ戦略や複雑な再検証ロジックが必要ないシンプルなユースケースで選定されます。
SWR is a React Hooks library for data fetching.
The name “SWR” is derived from stale-while-revalidate, a cache invalidation strategy popularized by HTTP RFC 5861.
SWR first returns the data from cache (stale), then sends the request (revalidate), and finally comes with the up-to-date data again.
With just one hook, you can significantly simplify the data fetching logic in your project. And it also covered in all aspects of speed, correctness, and stability to help you build better experiences:
...and a lot more.
With SWR, components will get a stream of data updates constantly and automatically. Thus, the UI will be always fast and reactive.
View full documentation and examples on swr.vercel.app.
import useSWR from 'swr'
function Profile() {
const { data, error, isLoading } = useSWR('/api/user', fetcher)
if (error) return <div>failed to load</div>
if (isLoading) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
In this example, the React Hook useSWR accepts a key and a fetcher function.
The key is a unique identifier of the request, normally the URL of the API. And the fetcher accepts
key as its parameter and returns the data asynchronously.
useSWR also returns 3 values: data, isLoading and error. When the request (fetcher) is not yet finished,
data will be undefined and isLoading will be true. When we get a response, it sets data and error based on the result
of fetcher, isLoading to false and rerenders the component.
Note that fetcher can be any asynchronous function, you can use your favourite data-fetching
library to handle that part.
View full documentation and examples on swr.vercel.app.
This library is created by the team behind Next.js, with contributions from our community:
Thanks to Ryan Chen for providing the awesome swr npm package name!
The MIT License.