### Download and Install SWR Example
Source: https://github.com/vercel/swr/blob/main/examples/suspense-global/README.md
Use these commands to download the example code, install dependencies, and start the development server.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/suspense
cd suspense
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Download and Install SWR Example
Source: https://github.com/vercel/swr/blob/main/examples/local-state-sharing/README.md
Use these commands to download the example code, install dependencies, and start the development server.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/local-state-sharing
cd local-state-sharing
yarn
yarn dev
```
```bash
npm install
npm run dev
```
--------------------------------
### Download and Install Example Project
Source: https://github.com/vercel/swr/blob/main/examples/infinite/README.md
Use these commands to download the example project and install its dependencies.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/infinite
cd basic
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Download and Setup SWR Storage Tab Sync Example
Source: https://github.com/vercel/swr/blob/main/examples/storage-tab-sync/README.md
Use these bash commands to download the example project and install its dependencies.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/storage-tab-sync
cd storage-tab-sync
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Download and Install Example Project
Source: https://github.com/vercel/swr/blob/main/examples/api-hooks/README.md
Use these commands to download the example project and install its dependencies.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/api-hooks
cd api-hooks
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Download and Install SWR Example
Source: https://github.com/vercel/swr/blob/main/examples/focus-revalidate/README.md
Use these commands to download the focus-revalidate example, install its dependencies, and start the development server.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/focus-revalidate
cd focus-revalidate
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Download and Install Example
Source: https://github.com/vercel/swr/blob/main/examples/autocomplete-suggestions/README.md
Use these commands to download the example code and set up the project dependencies.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/autocomplete-suggestions
cd autocomplete-suggestions
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Download and Install Example
Source: https://github.com/vercel/swr/blob/main/examples/global-fetcher/README.md
Use curl to download the example and yarn or npm to install dependencies.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/global-fetcher
cd global-fetcher
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Download and Install SWR Example
Source: https://github.com/vercel/swr/blob/main/examples/basic/README.md
Use these commands to download the basic SWR example and install its dependencies.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/basic
cd basic
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Download and Install Example
Source: https://github.com/vercel/swr/blob/main/examples/optimistic-ui/README.md
Use curl to download the example code, then install dependencies with yarn or npm.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/optimistic-ui
cd optimistic-ui
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Download and Install SWR Example
Source: https://github.com/vercel/swr/blob/main/examples/prefetch-preload/README.md
Commands to download the example project and install dependencies using yarn or npm.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/prefetch-preload
cd prefetch-preload
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Download and Install SWR Example
Source: https://github.com/vercel/swr/blob/main/examples/refetch-interval/README.md
Use these commands to download the example code and install dependencies using Yarn or npm.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/refetch-interval
cd refetch-interval
```
```bash
yarn
yarn dev
# or
npm install
npm run dev
```
--------------------------------
### Install and Run Project with npm
Source: https://github.com/vercel/swr/blob/main/examples/infinite-scroll/README.md
Install project dependencies using npm and start the development server.
```bash
npm install
npm run dev
```
--------------------------------
### Download and Navigate Example
Source: https://github.com/vercel/swr/blob/main/examples/subscription/README.md
Use these bash commands to download the SWR subscription example and navigate into its directory.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/subscription
cd subscription
```
--------------------------------
### Install and Run Project with Yarn
Source: https://github.com/vercel/swr/blob/main/examples/infinite-scroll/README.md
Install project dependencies using Yarn and start the development server.
```bash
yarn
yarn dev
```
--------------------------------
### Install and Run SWR Project
Source: https://github.com/vercel/swr/blob/main/examples/basic-typescript/README.md
Install project dependencies using either Yarn or npm, then start the development server.
```bash
yarn
yarn dev
```
```bash
npm install
npm run dev
```
--------------------------------
### Download Example with Curl
Source: https://github.com/vercel/swr/blob/main/examples/optimistic-ui-immer/README.md
Use curl to download the example project. Ensure to strip the main directory and navigate into the example folder.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/optimistic-ui-immer
cd optimistic-ui-immer
```
--------------------------------
### Download Example with curl
Source: https://github.com/vercel/swr/blob/main/examples/infinite-scroll/README.md
Use curl to download the example code. Ensure you have tar installed to extract the archive.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/infinite-scroll
cd infinite-scroll
```
--------------------------------
### Download SWR Example
Source: https://github.com/vercel/swr/blob/main/examples/basic-typescript/README.md
Use curl to download the SWR example code. Ensure to strip unnecessary directories for a clean setup.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/basic-typescript
cd basic-typescript
```
--------------------------------
### Download Example Code
Source: https://github.com/vercel/swr/blob/main/examples/server-render/README.md
Use curl to download the example code. Ensure you strip the parent directory and navigate into the example folder.
```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/server-render
cd server-render
```
--------------------------------
### WebSocket Subscription Example
Source: https://github.com/vercel/swr/blob/main/_autodocs/05-useSWRSubscription.md
This example demonstrates how to use useSWRSubscription to connect to a WebSocket server and receive real-time chat messages. It handles message parsing, error handling, and closing the WebSocket connection when the component unmounts.
```typescript
import useSWRSubscription from 'swr/subscription'
function LiveChat() {
const { data: messages, error } = useSWRSubscription(
'/ws/chat',
(path, { next }) => {
const ws = new WebSocket(`ws://localhost:8080${path}`)
ws.onmessage = (event) => {
next(null, JSON.parse(event.data))
}
ws.onerror = (error) => {
next(error)
}
return () => {
ws.close()
}
}
)
if (error) return
Connection failed
return (
{messages?.map((msg, i) => (
{msg.text}
))}
)
}
```
--------------------------------
### Import from 'swr/subscription'
Source: https://github.com/vercel/swr/blob/main/_autodocs/INDEX.md
Provides an example of importing `useSWRSubscription` for real-time data subscriptions and its related types.
```typescript
import useSWRSubscription from 'swr/subscription'
import type { SWRSubscriptionResponse, SWRSubscription } from 'swr/subscription'
```
--------------------------------
### Run Development Server
Source: https://github.com/vercel/swr/blob/main/e2e/site/README.md
Use these commands to start the Next.js development server. Open http://localhost:3000 in your browser to view the application.
```bash
npm run dev
```
```bash
yarn dev
```
```bash
pnpm dev
```
--------------------------------
### Basic Preload Example
Source: https://github.com/vercel/swr/blob/main/_autodocs/06-mutate-and-preload.md
Demonstrates preloading data for a specific API endpoint before navigating to a page. This is useful in SSG contexts like getStaticProps.
```typescript
import { preload } from 'swr'
const fetcher = (url) => fetch(url).then(r => r.json())
// Preload before navigating
export async function getStaticProps() {
await preload('/api/user/123', fetcher)
return { props: {} }
}
```
--------------------------------
### Page Number Pagination with KeyLoader
Source: https://github.com/vercel/swr/blob/main/_autodocs/04-useSWRInfinite.md
Example of a KeyLoader function for simple page number pagination. It fetches pages sequentially based on the page index, starting from page 1.
```typescript
const getKey = (index) => {
return `/api/posts?page=${index + 1}`
}
```
--------------------------------
### Link Hover Prefetch Example
Source: https://github.com/vercel/swr/blob/main/_autodocs/06-mutate-and-preload.md
Shows how to preload data when a user hovers over a link, improving perceived performance for subsequent page loads. Requires Next.js Link component.
```typescript
import Link from 'next/link'
import { preload } from 'swr'
const fetcher = (url) => fetch(url).then(r => r.json())
function UserLink({ userId }) {
return (
preload(`/api/user/${userId}`, fetcher)}
>
User
)
}
```
--------------------------------
### Conditional Preload Example
Source: https://github.com/vercel/swr/blob/main/_autodocs/06-mutate-and-preload.md
Illustrates preloading data only when a certain condition is met, such as a search query exceeding a minimum length. This prevents unnecessary fetches.
```typescript
import { preload } from 'swr'
function SearchResults({ query }) {
useEffect(() => {
if (query.length > 2) {
// Only preload if search query is meaningful
preload(`/api/search?q=${query}`, (key) =>
fetch(key).then(r => r.json())
)
}
}, [query])
}
```
--------------------------------
### SSR Preload Example
Source: https://github.com/vercel/swr/blob/main/_autodocs/06-mutate-and-preload.md
Demonstrates preloading data on the server using getServerSideProps. The data is fetched and cached before the page is sent to the client.
```typescript
import { preload } from 'swr'
export async function getServerSideProps({ params }) {
const fetcher = (url) => fetch(`${process.env.API_URL}${url}`).then(r => r.json())
await preload(`/api/post/${params.id}`, fetcher)
return {
props: {},
revalidate: 60
}
}
function PostPage() {
const { data } = useSWR(`/api/post/${router.query.id}`, fetcher)
// Data is already loaded from preload
return
{data?.title}
}
```
--------------------------------
### Prefetch on Route Change Example
Source: https://github.com/vercel/swr/blob/main/_autodocs/06-mutate-and-preload.md
Shows how to preload data in response to a route change event, ensuring data is ready when the user navigates. This uses Next.js router hooks.
```typescript
import { useRouter } from 'next/router'
import { preload } from 'swr'
import { useEffect } from 'react'
function Navigation() {
const router = useRouter()
const fetcher = (url) => fetch(url).then(r => r.json())
useEffect(() => {
router.prefetch('/dashboard').then(() => {
preload('/api/dashboard-data', fetcher)
})
}, [router])
return
}
```
--------------------------------
### Cursor-based Pagination with KeyLoader
Source: https://github.com/vercel/swr/blob/main/_autodocs/04-useSWRInfinite.md
Example of a KeyLoader function for cursor-based pagination. It stops fetching when the previous page has no nextCursor. Handles the initial request with an empty cursor.
```typescript
const getKey = (index, previousPageData) => {
if (previousPageData && !previousPageData.nextCursor) return null
return `/api/posts?cursor=${index === 0 ? '' : previousPageData.nextCursor}`
}
```
--------------------------------
### Subscription with Dynamic Key
Source: https://github.com/vercel/swr/blob/main/_autodocs/05-useSWRSubscription.md
This example shows how to use a dynamic key with useSWRSubscription, allowing the subscription endpoint to change based on component props, such as a `userId`. The subscription is automatically managed when the key changes or becomes null.
```typescript
function StreamingData({ userId }) {
const { data: updates } = useSWRSubscription(
userId ? `/api/user/${userId}/stream` : null,
(path, { next }) => {
const eventSource = new EventSource(path)
eventSource.onmessage = (event) => {
next(null, JSON.parse(event.data))
}
return () => {
eventSource.close()
}
}
)
if (!userId) return
Select a user
return
{updates?.message}
}
```
--------------------------------
### Server-Sent Events (SSE) Subscription
Source: https://github.com/vercel/swr/blob/main/_autodocs/05-useSWRSubscription.md
This example shows how to use useSWRSubscription with Server-Sent Events (SSE) to receive live notifications. It sets up an EventSource, parses incoming messages, and handles connection errors.
```typescript
function LiveNotifications() {
const { data: notifications } = useSWRSubscription(
'/api/notifications',
(path, { next }) => {
const eventSource = new EventSource(path)
eventSource.onmessage = (event) => {
const notification = JSON.parse(event.data)
next(null, notification)
}
eventSource.onerror = () => {
next(new Error('Connection lost'))
eventSource.close()
}
return () => {
eventSource.close()
}
}
)
return (
{notifications && {notifications.message}}
)
}
```
--------------------------------
### Offset-based Pagination with KeyLoader
Source: https://github.com/vercel/swr/blob/main/_autodocs/04-useSWRInfinite.md
Example of a KeyLoader function for offset-based pagination. It stops fetching when the previous page returns no data. Fetches data in chunks of 10.
```typescript
const getKey = (index, previousPageData) => {
if (previousPageData && !previousPageData.length) return null // End reached
return `/api/posts?offset=${index * 10}&limit=10`
}
```
--------------------------------
### Configure Focus Throttle Interval
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Example of setting a custom minimum time between focus revalidations using SWRConfig Provider. This prevents rapid fetches if focus is lost and regained quickly.
```typescript
```
--------------------------------
### Shared Subscription with Reference Counting
Source: https://github.com/vercel/swr/blob/main/_autodocs/05-useSWRSubscription.md
This example illustrates how useSWRSubscription handles multiple subscribers to the same key. The actual subscription is created only once and shared among components, with the subscription being cleaned up only when the last component unmounts.
```typescript
// Multiple components can subscribe to the same key
// The actual subscription is only created once and shared
function ComponentA() {
const { data } = useSWRSubscription('shared-key', subscribe)
return
A: {data}
}
function ComponentB() {
const { data } = useSWRSubscription('shared-key', subscribe)
return
B: {data}
}
// The subscribe function is called only once
// It's unsubscribed when the last component unmounts
```
--------------------------------
### Apply Middleware for Custom Functionality
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Extend SWR's behavior by applying middleware functions. This example demonstrates a simple logger middleware that logs the key of each request before it's processed.
```typescript
const logger = (useSWRNext) => (key, fetcher, config) => {
console.log('[SWR]', key)
return useSWRNext(key, fetcher, config)
}
useSWR('/api/user', fetcher, { use: [logger] })
```
--------------------------------
### SWRInfiniteKeyLoader Type
Source: https://github.com/vercel/swr/blob/main/_autodocs/08-types-and-interfaces.md
Defines the function signature for loading keys in an infinite SWR setup. It takes the current index and previous page data to determine the next arguments.
```typescript
type SWRInfiniteKeyLoader<
Data = any,
Args extends Arguments = Arguments
> = (index: number, previousPageData: Data | null) => Args
```
--------------------------------
### Configure Loading Timeout and onLoadingSlow
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Example of setting a custom timeout for loading states and defining a callback to execute when the timeout is reached. This can be used to display a loading indicator or other UI feedback.
```typescript
useSWR('/api/slow', fetcher, {
loadingTimeout: 5000,
onLoadingSlow: () => showLoadingIndicator()
})
```
--------------------------------
### Enable Revalidation on Mount
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Example of explicitly enabling data revalidation when a component mounts. This ensures fresh data on initial render.
```typescript
useSWR('/api/user', fetcher, { revalidateOnMount: true })
```
--------------------------------
### Disable Revalidation if Stale
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Example of disabling revalidation even when cached data is stale. This relies solely on the cache until manually invalidated.
```typescript
useSWR('/api/immutable', fetcher, { revalidateIfStale: false })
```
--------------------------------
### Disable Revalidation on Reconnect
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Example of disabling automatic data revalidation when the network connection is restored. Use when offline data is acceptable.
```typescript
useSWR('/api/data', fetcher, { revalidateOnReconnect: false })
```
--------------------------------
### Import SWRConfig Context
Source: https://github.com/vercel/swr/blob/main/_autodocs/INDEX.md
Import the SWRConfig component for global configuration.
```typescript
import { SWRConfig } from 'swr'
```
--------------------------------
### SWR with Custom Configuration
Source: https://github.com/vercel/swr/blob/main/_autodocs/01-useSWR.md
Demonstrates configuring SWR with options like refreshInterval, revalidateOnFocus, dedupingInterval, onError, and fallbackData.
```typescript
const { data, error, isValidating, mutate } = useSWR(
'/api/user',
fetcher,
{
refreshInterval: 5000,
revalidateOnFocus: false,
dedupingInterval: 10000,
onError: (error) => console.error('Failed:', error),
fallbackData: { name: 'Loading...' }
}
)
```
--------------------------------
### Disable Revalidation on Focus
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Example of disabling automatic data revalidation when the window regains focus. Useful for preventing unnecessary fetches.
```typescript
useSWR('/api/user', fetcher, { revalidateOnFocus: false })
```
--------------------------------
### Import from 'swr/mutation'
Source: https://github.com/vercel/swr/blob/main/_autodocs/INDEX.md
Shows how to import the `useSWRMutation` hook and related types for handling mutations with SWR.
```typescript
import useSWRMutation from 'swr/mutation'
import type { SWRMutationResponse, MutationFetcher } from 'swr/mutation'
```
--------------------------------
### SWRInfiniteKeyLoader
Source: https://github.com/vercel/swr/blob/main/_autodocs/08-types-and-interfaces.md
Defines the function signature for loading keys in an infinite pagination context.
```APIDOC
## Infinite Specific Types
### SWRInfiniteKeyLoader
Function signature for infinite key loading:
```typescript
type SWRInfiniteKeyLoader<
Data = any,
Args extends Arguments = Arguments
> = (index: number, previousPageData: Data | null) => Args
```
```
--------------------------------
### Import SWR Functions and Config
Source: https://github.com/vercel/swr/blob/main/_autodocs/INDEX.md
Import utility functions and configuration hooks from the SWR library.
```typescript
import { mutate, preload, useSWRConfig } from 'swr'
```
--------------------------------
### Custom Cache Transform
Source: https://github.com/vercel/swr/blob/main/_autodocs/06-mutate-and-preload.md
Customize how data is populated into the cache using the `populateCache` option. This example adds a new item to an existing list in the cache.
```typescript
mutate('/api/items', newItem, {
populateCache: (newItem, currentItems) => {
// Add new item to existing list
return [...(currentItems || []), newItem]
}
})
```
--------------------------------
### Import useSWRInfinite
Source: https://github.com/vercel/swr/blob/main/_autodocs/04-useSWRInfinite.md
Import the useSWRInfinite hook from the 'swr/infinite' package.
```typescript
import useSWRInfinite from 'swr/infinite'
```
--------------------------------
### Configure Error Retry Interval
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Example of setting the initial interval for exponential backoff retries on error. This controls how quickly SWR attempts to refetch after a failure.
```typescript
useSWR('/api/data', fetcher, { errorRetryInterval: 10000 })
```
--------------------------------
### Import Default and Named Exports from 'swr'
Source: https://github.com/vercel/swr/blob/main/_autodocs/INDEX.md
Demonstrates how to import the default `useSWR` hook and other named exports like `SWRConfig`, `mutate`, `preload`, `useSWRConfig`, and `unstable_serialize` from the main 'swr' package.
```typescript
// Default export
import useSWR from 'swr'
// Named exports
import {
SWRConfig,
mutate,
preload,
useSWRConfig,
unstable_serialize
} from 'swr'
// Type exports
import type {
Key, Arguments, Fetcher, SWRResponse,
SWRConfiguration, Cache, Middleware,
// ... and 20+ more types
} from 'swr'
```
--------------------------------
### Basic Infinite Scroll with useSWRInfinite
Source: https://github.com/vercel/swr/blob/main/_autodocs/04-useSWRInfinite.md
Demonstrates a basic infinite scroll implementation using useSWRInfinite. It fetches pages of data and provides a button to load more.
```typescript
import useSWRInfinite from 'swr/infinite'
function PostList() {
const { data, size, setSize, isLoading } = useSWRInfinite(
(index) => `/api/posts?page=${index + 1}`,
fetcher
)
const posts = data ? data.flat() : []
return (
{posts.map((post) => (
{post.title}
))}
)
}
```
--------------------------------
### Error Handling and Retry with useSWRSubscription
Source: https://github.com/vercel/swr/blob/main/_autodocs/05-useSWRSubscription.md
Implement automatic retries for WebSocket connections using useSWRSubscription. This example includes exponential backoff and a maximum retry count.
```typescript
function RobustSubscription() {
const [retryCount, setRetryCount] = useState(0)
const { data, error } = useSWRSubscription(
['live-data', retryCount],
(key, { next }) => {
const ws = new WebSocket('wss://api.example.com/stream')
ws.onmessage = (e) => {
next(null, JSON.parse(e.data))
setRetryCount(0) // Reset on success
}
ws.onerror = (error) => {
next(error)
}
return () => ws.close()
}
)
useEffect(() => {
if (error && retryCount < 3) {
const timer = setTimeout(() => {
setRetryCount((c) => c + 1)
}, 2000 * (retryCount + 1)) // Exponential backoff
return () => clearTimeout(timer)
}
}, [error, retryCount])
return (
{data &&
{data}
}
{error && retryCount < 3 &&
Reconnecting... ({retryCount}/3)
}
{error && retryCount >= 3 &&
Connection failed
}
)
}
```
--------------------------------
### Global Configuration with SWRConfig
Source: https://github.com/vercel/swr/blob/main/_autodocs/README.md
Configure SWR globally using `SWRConfig.Provider`. This is useful for setting default fetchers, deduping intervals, and other options for all hooks within the provider.
```typescript
import { SWRConfig } from 'swr'
```
--------------------------------
### Batch Update with Filter
Source: https://github.com/vercel/swr/blob/main/_autodocs/06-mutate-and-preload.md
Update multiple cache entries simultaneously by providing a filter function that matches keys. This example clears all matching cache entries.
```typescript
// Update all keys matching a pattern
mutate(
(key) => typeof key === 'string' && key.startsWith('/api/posts'),
undefined,
{ revalidate: true }
)
```
--------------------------------
### Handle Fetch Errors with onError
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Implement error handling logic using the `onError` callback when a data fetch fails. This example logs the error and displays a notification.
```typescript
useSWR('/api/data', fetcher, {
onError: (error) => {
console.error('Failed to load:', error)
showErrorNotification(error.message)
}
})
```
--------------------------------
### Use Custom Shallow Comparison
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Replace the default deep equality comparison with a custom function for detecting data changes. This example uses shallow comparison (`===`).
```typescript
useSWR('/api/items', fetcher, {
compare: (a, b) => a === b
})
```
--------------------------------
### Import useSWRConfig
Source: https://github.com/vercel/swr/blob/main/_autodocs/02-useSWRConfig-and-SWRConfig.md
Import the useSWRConfig hook from the 'swr' library.
```typescript
import { useSWRConfig } from 'swr'
```
--------------------------------
### Import preload Function
Source: https://github.com/vercel/swr/blob/main/_autodocs/06-mutate-and-preload.md
Import the preload function from the 'swr' library.
```typescript
import { preload } from 'swr'
```
--------------------------------
### Polling with Exponential Backoff in SWR
Source: https://github.com/vercel/swr/blob/main/_autodocs/10-middleware-and-advanced-patterns.md
Implement polling that adjusts its interval based on data changes, increasing the interval when no updates occur. This example uses `useState` to control the `refreshInterval`.
```typescript
function SmartPolling() {
const [pollInterval, setPollInterval] = useState(1000)
const { data: status } = useSWR(
'/api/job-status',
fetcher,
{ refreshInterval: pollInterval }
)
useEffect(() => {
if (!status) return
if (status.isComplete) {
setPollInterval(0) // Stop polling
} else if (status.progress < 50) {
setPollInterval(1000) // Fast poll for initial progress
} else {
setPollInterval(5000) // Slower poll as it gets closer to done
}
}, [status])
return
Progress: {status?.progress}%
}
```
--------------------------------
### Import SWR Types
Source: https://github.com/vercel/swr/blob/main/_autodocs/INDEX.md
Import various types for defining SWR keys, fetchers, responses, and configurations.
```typescript
import type {
Key,
Arguments,
Fetcher,
BareFetcher,
SWRResponse,
SWRConfiguration,
PublicConfiguration,
Cache,
Middleware,
// ... and more
} from 'swr'
```
--------------------------------
### Custom Visibility Detection with isVisible
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Utilize the `isVisible` function for custom window visibility detection in specific environments. This example demonstrates passing a custom visibility API to `useSWR`.
```typescript
useSWR('/api/data', fetcher, {
isVisible: () => customVisibilityAPI.isVisible()
})
```
--------------------------------
### Basic Data Fetching with useSWR
Source: https://github.com/vercel/swr/blob/main/README.md
Use the `useSWR` hook to fetch data. It accepts a unique key (like a URL) and a fetcher function. It returns data, error state, and loading status.
```javascript
import useSWR from 'swr'
function Profile() {
const { data, error, isLoading } = useSWR('/api/user', fetcher)
if (error) return
failed to load
if (isLoading) return
loading...
return
hello {data.name}!
}
```
--------------------------------
### Configure Deduping Interval
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Example of setting a custom time window for automatic request deduplication. Multiple `useSWR` calls with the same key within this interval will share a single request.
```typescript
useSWR('/api/user', fetcher, { dedupingInterval: 5000 })
```
--------------------------------
### RxJS Observable Subscription
Source: https://github.com/vercel/swr/blob/main/_autodocs/05-useSWRSubscription.md
This example shows how to integrate RxJS Observables with useSWRSubscription to manage real-time data streams. It subscribes to an interval observable and updates the component with the emitted values.
```typescript
import { interval, map } from 'rxjs'
function ObservableCounter() {
const { data: count } = useSWRSubscription(
'counter',
(key, { next }) => {
const subscription = interval(1000)
.pipe(map((x) => x + 1))
.subscribe({
next: (value) => {
next(null, value)
},
error: (error) => {
next(error)
}
})
return () => subscription.unsubscribe()
}
)
return
Count: {count}
}
```
--------------------------------
### Global Configuration with SWRConfig
Source: https://github.com/vercel/swr/blob/main/_autodocs/INDEX.md
Provides a way to set default configurations for all SWR hooks within a React component tree using a Provider.
```APIDOC
## SWRConfig
### Description
Sets default configuration options for all SWR hooks used within its subtree.
### Usage
```jsx
import { SWRConfig } from 'swr'
function App() {
return (
{/* Other components */}
)
}
```
### Parameters
- **value**: `SWRConfiguration` - An object containing default configuration options.
```
--------------------------------
### Composing Middleware with SWRConfig
Source: https://github.com/vercel/swr/blob/main/_autodocs/10-middleware-and-advanced-patterns.md
Apply multiple middleware functions in sequence by providing an array to the `use` option within `SWRConfig.Provider`. Middleware are executed in the order they appear in the array.
```typescript
```
--------------------------------
### Access SWR Configuration in a Component
Source: https://github.com/vercel/swr/blob/main/_autodocs/02-useSWRConfig-and-SWRConfig.md
Use the useSWRConfig hook to get access to the cache, global mutate function, and other configuration options like refreshInterval within a React component.
```typescript
import { useSWRConfig, mutate } from 'swr'
function MyComponent() {
const { cache, mutate: globalMutate, refreshInterval } = useSWRConfig()
const clearAllCache = () => {
for (const key of cache.keys()) {
cache.delete(key)
}
}
const revalidateAll = () => {
globalMutate(() => true)
}
return (
Refresh interval: {refreshInterval}ms
)
}
```
--------------------------------
### Pre-populate Cache with Fallback Data
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Initialize the SWR cache with data for multiple keys using the `fallback` option within `SWRConfig.Provider`. Ideal for Server-Side Rendering (SSR) hydration or bulk cache initialization.
```typescript
```
--------------------------------
### Notify on Slow Requests with onLoadingSlow
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Be notified when a fetch request takes longer than the specified `loadingTimeout` using the `onLoadingSlow` callback. This example logs a warning and shows a slow loading indicator.
```typescript
useSWR('/api/slow-endpoint', fetcher, {
loadingTimeout: 3000,
onLoadingSlow: (key) => {
console.warn(`Request to ${key} is taking longer than expected`)
showSlowLoadingIndicator()
}
})
```
--------------------------------
### Global Middleware with SWRConfig
Source: https://github.com/vercel/swr/blob/main/_autodocs/INDEX.md
Apply middleware globally to all SWR hooks within the application by wrapping the root component with `SWRConfig.Provider`.
```typescript
```
--------------------------------
### Configure Conditional Retry on Errors
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Define a function to determine whether to retry on error based on the error object. This allows for selective retries, for example, excluding 404 or 403 errors.
```typescript
useSWR('/api/data', fetcher, {
shouldRetryOnError: (error) => {
return error.status !== 404 && error.status !== 403
}
})
```
--------------------------------
### Understand SWR Configuration Cascading
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Observe how SWR merges configurations: default config, global SWRConfig.Provider, and hook-specific options. Later configurations overwrite earlier ones.
```typescript
// Default: revalidateOnFocus: true
{/* Now: revalidateOnFocus: false for all hooks */}
{/* revalidateOnFocus: false */}
{/* revalidateOnFocus: true - overrides global */}
```
--------------------------------
### Preload with Array Keys
Source: https://github.com/vercel/swr/blob/main/_autodocs/06-mutate-and-preload.md
Demonstrates using an array as a cache key for preloading data. This is useful when the fetcher requires multiple arguments.
```typescript
import { preload } from 'swr'
const fetcher = ([url, id]) => fetch(`${url}/${id}`).then(r => r.json())
// Preload with array key
preload(['/api/user', 123], fetcher)
```
--------------------------------
### Static Content with Hash
Source: https://github.com/vercel/swr/blob/main/_autodocs/07-useSWRImmutable.md
Include a content hash in the URL when fetching static assets to ensure immutability. This is useful for cache-busting and ensuring users always get the correct version of a file.
```typescript
import useSWRImmutable from 'swr/immutable'
function StaticAsset() {
// Include content hash in URL to make it immutable
const { data } = useSWRImmutable(
`/assets/chunk.abc123.js`,
fetcher
)
return
}
```
--------------------------------
### Global SWR Configuration
Source: https://github.com/vercel/swr/blob/main/_autodocs/00-START-HERE.txt
Configure SWR globally by wrapping your application with `SWRConfig.Provider`. This is useful for setting a default `fetcher` function or other configuration options for all SWR hooks.
```javascript
```
--------------------------------
### Handle Discarded Requests with onDiscarded
Source: https://github.com/vercel/swr/blob/main/_autodocs/09-configuration-reference.md
Log or perform cleanup actions when a request is discarded due to race conditions using the `onDiscarded` callback. This example logs a message indicating the request was discarded.
```typescript
useSWR('/api/data', fetcher, {
onDiscarded: (key) => {
console.log(`Request for ${key} was discarded`)
}
})
```