How to use SWR in React
SWR (Stale-While-Revalidate) is a powerful data fetching library that provides automatic caching, revalidation, and error handling out of the box. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented SWR in production React applications throughout my 11 years of development experience. The most straightforward approach is using the useSWR hook with a fetcher function for automatic data management. This method handles caching, background updates, and loading states automatically without manual state management.
Install SWR and use the useSWR hook with a fetcher function for data fetching.
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then(res => res.json())
const UserProfile = () => {
const { data, error, isLoading } = useSWR('/api/user', fetcher)
if (error) return <div>Failed to load</div>
if (isLoading) return <div>Loading...</div>
return (
<div>
<h1>{data.name}</h1>
<p>{data.email}</p>
</div>
)
}
Here the useSWR hook takes a key (the API URL) and a fetcher function. It automatically handles caching, so subsequent requests return cached data immediately while revalidating in the background. The hook returns data, error, and loading state, eliminating manual state management. SWR also handles focus revalidation, network recovery, and polling automatically.
Best Practice Note:
This is the approach we recommend for CoreUI React applications requiring robust data fetching with minimal boilerplate. Configure global settings with SWRConfig for consistent behavior across your app, use mutate for optimistic updates, and leverage conditional fetching with null keys for dependent requests.



