Course contentsShow
← React
Lesson 1809 of 2,39642. Data Fetching LibrariesFree lesson

Global Configuration and SWRConfig

Setting up global fetcher functions, default options, and context-based configuration across your app.

Global Configuration and SWRConfig

What you'll learn: How to set default fetcher functions and configuration options across your entire SWR-powered app using SWRConfig.

The Configuration Provider Pattern

Instead of passing the same fetcher function and options to every useSWR call, SWR provides SWRConfig — a context provider that establishes defaults for all hooks within its tree. Think of it as setting house rules once at the entrance rather than explaining them to every guest individually.

Setting Up Global Defaults

Wrap your app (or a section of it) with SWRConfig and provide a configuration object:

import { SWRConfig } from 'swr';

const fetcher = (url) => fetch(url).then(res => res.json());

function App() {
  return (
    <SWRConfig 
      value={{
        fetcher,
        revalidateOnFocus: false,
        dedupingInterval: 5000,
        refreshInterval: 30000
      }}
    >
      <YourComponents />
    </SWRConfig>
  );
}

Now every useSWR hook inside <YourComponents /> inherits these settings without needing to specify them individually.

Overriding Globals Locally

Individual hooks can still override these defaults when needed:

// Uses global fetcher and settings
const { data } = useSWR('/api/posts');

// Overrides revalidateOnFocus locally
const { data: user } = useSWR('/api/user', { 
  revalidateOnFocus: true 
});

Nested Configuration

You can nest SWRConfig providers to create configuration layers — inner providers merge with and override outer ones, perfect for feature-specific settings.

Key Takeaway: SWRConfig eliminates repetition by establishing global defaults for fetchers and options, while still allowing per-hook customization when you need it.