How to Debug SWR in React
This article explores the most effective methods for debugging the SWR (Stale-While-Revalidate) data-fetching library in React applications. You will learn how to use dedicated developer tools, implement global logging middleware, and leverage browser inspection techniques to monitor cache states, revalidations, and network requests.
1. Use SWR DevTools
The easiest way to visualize your SWR cache is by using SWR DevTools. This is a browser extension and library combination that helps you inspect the current state of your SWR cache, see which keys are active, and track cache transitions in real-time.
To use it: 1. Install the SWR DevTools extension for
Chrome or Firefox. 2. Install the companion package in your project:
bash npm install swr-devtools 3. Wrap your application
(or the SWRConfig provider) with the DevTools component:
```jsx import { SWRConfig } from ‘swr’; import SWRDevTools from
‘swr-devtools’;
function App() { return (
2. Implement a Logging Middleware
SWR supports middleware, which allows you to inspect and modify arguments, key changes, and cache transitions. You can write a simple logging middleware to print cache updates and fetches directly to your browser’s console.
Create a custom middleware like this:
function logger(useSWRNext) {
return (key, fetcher, config) => {
const extendedFetcher = (...args) => {
console.log(`[SWR Fetch] Key: ${key}`);
return fetcher(...args);
};
const swr = useSWRNext(key, extendedFetcher, config);
console.log(`[SWR State] Key: ${key}`, {
data: swr.data,
error: swr.error,
isValidating: swr.isValidating
});
return swr;
};
}You can then apply this middleware globally using
<SWRConfig>:
<SWRConfig value={{ use: [logger] }}>
<App />
</SWRConfig>3. Leverage SWRConfig Global Event Handlers
If you want to debug errors or slow network requests globally, you
can utilize the event handlers provided by SWRConfig. This
is highly effective for identifying failed fetches or performance
bottlenecks without cluttering individual components.
Configure global logging handlers inside your root
SWRConfig:
<SWRConfig
value={{
onError: (error, key) => {
console.error(`[SWR Error] Failed to fetch key: ${key}`, error);
},
onLoadingSlow: (key, config) => {
console.warn(`[SWR Warning] Fetching key "${key}" is taking longer than ${config.loadingTimeout}ms`);
},
onSuccess: (data, key) => {
console.log(`[SWR Success] Successfully fetched key: ${key}`, data);
}
}}
>
<App />
</SWRConfig>4. Inspect the Network Tab and Deduplication
SWR deduplicates requests that occur within a specific time span (defaulting to 2 seconds). If you expect a network request to fire but nothing appears in your browser’s Network tab, it is likely due to deduplication or caching.
To verify this, you can adjust the deduplication interval or force
revalidations: * Check deduplication: Temporarily set
dedupingInterval: 0 in your hook configuration to force SWR
to make a network request on every component mount. * Inspect
the Cache: You can directly inspect the global SWR cache map by
importing the useSWRConfig hook and accessing the cache
provider:
javascript const { cache } = useSWRConfig(); console.log(cache.get('your-api-key'));