The useSWR Hook API
What you'll learn: How SWR's hook signature works, how it uses keys for caching, and how to write basic fetcher functions.
The Hook Signature
SWR revolves around a single hook with a straightforward API:
const { data, error, isLoading } = useSWR(key, fetcher)
The hook takes two main arguments: a key (usually a string like a URL) and a fetcher function that actually retrieves the data. The key serves double duty—it identifies what data you want AND acts as the cache identifier.
The Key-Based Approach
Think of the key as both a question and a filing system label. When you write:
useSWR('/api/user', fetcher)
You're saying "fetch user data" AND "store it under the label '/api/user'". Any other component using that same key will share the cached result automatically. This is why SWR can deduplicate requests—multiple components with the same key reference the same cache entry.
The Fetcher Function
The fetcher is your custom function that knows how to turn a key into data. SWR doesn't assume you're using fetch or axios—you bring your own:
const fetcher = (url) => fetch(url).then(res => res.json())
function Profile() {
const { data, error, isLoading } = useSWR('/api/user', fetcher)
if (isLoading) return <div>Loading...</div>
if (error) return <div>Failed to load</div>
return <div>Hello {data.name}!</div>
}
The fetcher receives the key as its first argument, so it knows what to fetch.
Key Takeaway: SWR's useSWR(key, fetcher) hook uses the key for both cache identification and as the fetcher's argument, creating an elegant system where the "what" (key) and "how" (fetcher) are cleanly separated.