React Query vs SWR: どちらのデータフェッチャを選ぶか
React Query(TanStack Query)はフル機能のサーバー状態マネージャで、SWRは軽量でfocusされたstale-while-revalidateのデータフェッチャです。
TanStack Queryは、キャッシュ、バックグラウンドでの再フェッチ、ページネーション、mutation、無効化、オフラインサポートを豊富なAPIで扱い、完全なサーバー状態のソリューションになります。SWR(Vercel製)は、より小さな表面を持つ最小限のstale-while-revalidateのhookにfocusし、読み取りの多いアプリと緊密なNext.js統合に適しています。React Queryは機能とmutationツールで優れ、SWRはミニマリズムと小さくfocusされたAPIで優れます。
| React Query | SWR | |
|---|---|---|
| スコープ | フル機能のサーバー状態マネージャ | focusされたフェッチャ |
| mutation | 豊富、組み込み | より軽量 |
| APIの表面 | 大きい | 最小限 |
| devtools | 優秀 | 基本的 |
| 最適な用途 | 複雑なサーバー状態 | 読み取りの多い軽量なフェッチ |
ユースケースと機能
React Queryは、複雑なサーバー状態を持つアプリに向いています。多数のmutation、無効化のグラフ、ページネーション、オフラインの要件を、強力なdevtoolsで支えます。SWRは、良好なNext.js統合を備えた小さく使い勝手のよいフェッチャを求める、よりシンプルで読み取りの多いアプリに向いています。どちらもstale-while-revalidateの哲学を共有します。
テストとCI
どちらもMSWのようなfetchインターセプタでクリーンにモックできます。いずれもマネージドrunner上で実行でき、より高速なrunnerはデータフェッチと統合のテストスイートを短縮します。
Decide with your own numbers, not a feature table
Feature comparisons age badly and rarely decide anything, because both tools in a mature category can do the job. What differs is how each behaves on your repository, and that takes one afternoon to measure.
# time a cold install with each candidate, cache cleared
hyperfine --prepare "rm -rf node_modules" --warmup 1 \
"<tool-a> install" "<tool-b> install"
# and the thing CI actually pays for: a cold run with no local cache
docker run --rm -v "$(pwd):/w" -w /w node:22 sh -c "<tool> install"What actually changes when you switch
- Lockfile format. A switch is a one-way door for anyone still on the old tool until everyone migrates, so plan it as a single coordinated change.
- Resolution strictness. Tools differ on whether an undeclared transitive import works, and the stricter one will surface latent bugs as new failures.
- CI cache configuration. The cache path and key differ per tool; carrying over the old ones silently disables caching.
- Everyone on the team and every runner must move together. Pin the version so they cannot drift.
結論
豊富なmutation、無効化、ページネーション、強力なdevtoolsが必要なら: React Query。読み取りの多いアプリ向けに最小限でfocusされたフェッチャが欲しいなら: SWR。React Queryはより完全なサーバー状態のソリューションで、SWRは軽量で使い勝手のよい選択肢です。