SWR mit Claude Code: Data Fetching für React 2026
SWR (stale-while-revalidate) von Vercel ist die elegante Alternative zu TanStack Query für React-Data-Fetching — automatisches Caching, Revalidierung, Mutation und Optimistic Updates mit minimalem API. Claude Code nutzt SWR idiomatisch und effizient.
SWR Grundlagen: useSWR
SWRDas stale-while-revalidate Prinzip
# Prompt: "Implementiere Data Fetching für eine User-Liste mit SWR,
# Fehlerbehandlung und Loading States"
import useSWR from 'swr'
// Globaler Fetcher (einmalig konfigurieren):
const fetcher = (url: string) =>
fetch(url).then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
})
// SWRConfig: globale Konfiguration
export function Providers({ children }) {
return (
<SWRConfig value={{ fetcher, revalidateOnFocus: false }}>
{children}
</SWRConfig>
)
}
// useSWR in Komponente:
function UserList() {
const { data, error, isLoading } = useSWR<User[]>('/api/users')
if (isLoading) return <Skeleton />
if (error) return <ErrorMessage error={error} />
return <ul>{data?.map(u => <UserCard key={u.id} user={u} />)}</ul>
}
// SWR Key = URL: automatisch gecacht + dedupliziert
// Gleichzeitig 10 Komponenten mit useSWR('/api/users') → 1 Request!
Mutation und Optimistic Updates
OptimisticSofortige UI-Updates
# Prompt: "Implementiere Like-Button mit Optimistic Update —
# UI sofort aktualisieren, bei Fehler zurückrollen"
import useSWRMutation from 'swr/mutation'
function LikeButton({ postId }: { postId: string }) {
const { data: post, mutate } = useSWR<Post>(`/api/posts/${postId}`)
async function toggleLike() {
// Optimistic Update: sofort im Cache ändern
await mutate(
async (current) => {
// Auf Server senden (im Hintergrund)
await fetch(`/api/posts/${postId}/like`, { method: 'POST' })
// Optimistisch: likes+1
return { ...current!, likes: current!.likes + 1 }
},
{ optimisticData: { ...post!, likes: post!.likes + 1 },
rollbackOnError: true } // Bei Fehler: automatisch zurück!
)
}
return (
<button onClick={toggleLike}>
♥ {post?.likes}
</button>
)
}
Infinite Loading
InfiniteUnendliches Scrollen
# Prompt: "Implementiere Infinite Scroll mit useSWRInfinite"
import useSWRInfinite from 'swr/infinite'
const PAGE_SIZE = 20
function getKey(pageIndex: number, previousData: Post[] | null) {
if (previousData && !previousData.length) return null // Ende erreicht
return `/api/posts?page=${pageIndex}&limit=${PAGE_SIZE}`
}
function PostFeed() {
const { data, size, setSize, isValidating } = useSWRInfinite<Post[]>(getKey)
const posts = data?.flat() ?? []
const isLoadingMore = isValidating && size > 1
const hasMore = data?.[data.length - 1]?.length === PAGE_SIZE
return (
<div>
{posts.map(post => <PostCard key={post.id} post={post} />)}
{hasMore && (
<button
onClick={() => setSize(size + 1)}
disabled={isLoadingMore}
>
{isLoadingMore ? 'Lädt...' : 'Mehr laden'}
</button>
)}
</div>
)
}
SWR vs. TanStack Query: SWR ist leichter (~4KB) und einfacher zu lernen. TanStack Query bietet mehr Features (Background Refetching, Offline Support, DevTools). Claude Code wählt automatisch das richtige Tool für euren Use Case.
Data Fetching Modul im Kurs
Im Claude Code Mastery Kurs: vollständiges Data Fetching Modul mit SWR, TanStack Query, Optimistic Updates, Infinite Loading und Server-State-Management.
14 Tage kostenlos testen →