swr vs react-query vs axios-hooks
React 用データフェッチングライブラリの比較と選定ガイド
swrreact-queryaxios-hooks類似パッケージ:

React 用データフェッチングライブラリの比較と選定ガイド

axios-hooks、react-query(現在は @tanstack/react-query)、swr は、React アプリケーションにおけるサーバー状態の管理とデータフェッチングを簡素化するためのライブラリです。axios-hooks は Axios をフックとしてラップすることに特化しており、既存の Axios 環境との親和性が高いです。react-query は強力なキャッシュ機能とバックグラウンド更新を提供し、複雑なサーバー状態の管理に適しています。swr は Vercel によって開発され、軽量でシンプルな API を特徴とし、特に Next.js との相性が良い設計になっています。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
swr19,431,59032,492320 kB2362ヶ月前MIT
react-query1,735,33350,4222.26 MB1674年前MIT
axios-hooks46,6571,88947.1 kB62年前MIT

axios-hooks vs react-query vs swr:アーキテクチャと実装の比較

React におけるデータフェッチングは、コンポーネントのライフサイクルと非同期処理をどう統合するかという課題です。axios-hooks、react-query、swr はそれぞれ異なるアプローチでこの問題を解決します。ここでは、実装の詳細、キャッシュ戦略、そして保守性の観点から技術的な比較を行います。

🎯 基本的なデータ取得:フックの使い勝手

各ライブラリは、データ取得の状態をコンポーネントに提供するフックを提供していますが、その API デザインには明確な違いがあります。

axios-hooks は Axios のインスタンスを直接使用することを前提としています。

  • 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 はクエリキーを用いてキャッシュを識別します。

  • 第一引数にキー、第二引数にフェッチ関数を渡します。
  • Axios に限定されず、任意のフェッチ関数を使用可能です。
// 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 引数を取ります。
  • キーが null の場合、フェッチを自動で一時停止します。
// 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 を使って手動でトリガーする必要があります。
  • 楽観的更新(Optimistic Updates)は自分で実装する必要があります。
// 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 エコシステムに依存します。

  • Axios を使わないプロジェクトでは採用意義が薄れます。
  • 機能拡張よりも、Axios のラッパーとしての安定性が重視されます。

react-query は TanStack 傘下に移行しました。

  • 旧パッケージ名 react-query は v3 で終了し、現在は @tanstack/react-query が公式です。
  • React 以外(Vue、Svelte 等)でも使えるコアロジックを持っています。

swr は Vercel によってメンテナンスされています。

  • Next.js との統合が強く、エッジケースへの対応が速いです。
  • 軽量さを保ちながら必要な機能を追加する方針です。

📊 比較サマリー

機能axios-hooksreact-queryswr
主な用途Axios リクエスト管理複雑なサーバー状態軽量キャッシュ
キャッシュ最小限高度な制御可能自動(SWR 戦略)
ミューテーション手動トリガーuseMutation 専用useSWRMutation
依存関係Axios 必須任意のフェッチ任意のフェッチ
保守状況維持中活発(TanStack)活発(Vercel)

💡 結論:プロジェクトに合った選択を

axios-hooks は、Axios 依存のレガシーコードを整理したい場合や、キャッシュ機能よりもリクエストの簡素化を優先する場合に有効です。ただし、現代的なデータフェッチングの要件(キャッシュ、再検証など)を満たすには追加の工夫が必要です。

react-query (@tanstack/react-query)は、機能性と拡張性が最優先される場合に最適です。大規模なアプリケーションでサーバー状態を厳密に管理したいなら、これが標準的な選択になります。

swr は、シンプルさとパフォーマンスのバランスを重視する場合に適しています。特に Next.js を使用している場合、摩擦なく導入できるでしょう。

最終的には、チームの技術スタックと、アプリケーションが求めるデータの鮮度管理の複雑さによって決定すべきです。

選び方: swr vs react-query vs axios-hooks

  • swr:

    軽量なフックを好む場合や、Next.js などの Vercel エコシステム上で開発を行う場合に適しています。設定を最小限に抑えつつ、stale-while-revalidate 戦略による基本的なキャッシュと再検証機能をすぐに導入したいプロジェクトで選定されます。

  • react-query:

    複雑なサーバー状態の管理、高度なキャッシュ制御、ミューテーション(データ更新)の最適化が必要な大規模アプリケーションに適しています。現在は @tanstack/react-query としてメンテナンスされており、エコシステムが最も充実しているため、長期的な保守性を重視するプロジェクトで推奨されます。

  • axios-hooks:

    既存のプロジェクトで Axios をすでに多用しており、新しいキャッシュ層を導入せずにリクエスト状態(ローディング、エラー、データ)だけをフックで管理したい場合に適しています。大規模なキャッシュ戦略や複雑な再検証ロジックが必要ないシンプルなユースケースで選定されます。

swr のREADME

SWR


Introduction

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:

  • Fast, lightweight and reusable data fetching
  • Transport and protocol agnostic
  • Built-in cache and request deduplication
  • Real-time experience
  • Revalidation on focus
  • Revalidation on network recovery
  • Polling
  • Pagination and scroll position recovery
  • SSR and SSG
  • Local mutation (Optimistic UI)
  • Built-in smart error retry
  • TypeScript
  • React Suspense
  • React Native

...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.


Quick Start

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.


Authors

This library is created by the team behind Next.js, with contributions from our community:

Contributors

Thanks to Ryan Chen for providing the awesome swr npm package name!


License

The MIT License.