SWR: React Hooks for Remote Data Fetching

repository·main·Indexed 12 days ago

https://github.com/vercel/swr

SWR is a React Hooks library for data fetching (version 2.5.0) that implements the 'stale-while-revalidate' strategy. It provides fast, reactive, and lightweight data fetching with built-in caching and automatic revalidation. Key features include the useSWR and useSWRInfinite hooks, global fetcher configuration via SWRConfig, optimistic UI updates using mutate, and support for TypeScript type safety.

Tokens
10K
Snippets
40
Records
60
Agent score
98%

What's inside SWR

  1. Core features of SWR

    main

    SWR provides a reactive and fast data-fetching experience with several built-in capabilities:

    • Caching & Deduplication: Built-in cache and request deduplication.
    • Automatic Revalidation: Revalidation on focus, revalidation on network recovery, and polling.
    • Advanced UI Patterns: Support for Pagination, Scroll position recovery, and Local mutation (Optimistic UI).
    • Compatibility: Transport and protocol agnostic, supports SSR, SSG, React Suspense, and React Native.
    • Resilience: Built-in smart error retry.
  2. Set up a global fetcher with SWRConfig

    main

    Instead of providing a fetcher function to every individual useSWR hook call, you can define a global fetcher using the SWRConfig provider. This allows all useSWR hooks within the provider's component tree to share the same fetching logic automatically.

    // Use the SWRConfig provider to set up the fetcher globally
    <SWRConfig value={{ fetcher: myGlobalFetcher }}>
      <App />
    </SWRConfig>
  3. Understand the Focus Revalidate concept

    main
    The Focus Revalidate example demonstrates SWR's ability to revalidate data when the window regains focus. It specifically showcases how to implement basic authentication and how to trigger revalidation on a per-hook call basis using the revalidate on focus feature.
  4. Implement Server-Side Rendering with SWR and Next.js

    main

    To support Server-Side Rendering (SSR) with SWR, combine Next.js getServerSideProps with the SWR fallbackData option.

    The Workflow:

    1. Server-side: Fetch the required data within getServerSideProps.
    2. Hydration: Pass that fetched data to your component as props.
    3. Client-side: Pass the props into the SWR hook using the fallbackData option. This ensures the UI is populated immediately with the server-provided data.
    4. Revalidation: Once the application becomes interactive on the client, SWR will automatically revalidate the data against the API to ensure it is up-to-date, updating the DOM only if the data has changed.
  5. Use SWR with React Suspense

    main
    The SWR suspense example demonstrates how to enable the suspense option within the useSWR hook. When suspense: true is passed in the configuration, SWR will trigger a React Suspense boundary while the data is being fetched, allowing you to show a fallback UI (like a loading spinner) defined in a parent <Suspense> component.
  6. Share local state between React components using SWR

    main
    The local-state-sharing example demonstrates the pattern of using SWR to manage and share state locally within a React application, allowing multiple components to access and react to the same piece of state without complex prop drilling or external state management libraries.
  7. Implement Optimistic UI with SWR

    main
    Optimistic UI is a pattern where you mutate cached data immediately to provide an instant response to user actions, then trigger a revalidation with the API to ensure the local state eventually synchronizes with the server. In SWR, this is typically achieved by using the mutate function to update the local cache before or during the API call.
  8. Create custom hooks using SWR

    main
    The api-hooks example demonstrates a core architectural pattern: using SWR internally within custom hooks to manage different data requirements. Instead of calling useSWR directly in your components, you can encapsulate the fetching logic, key management, and configuration inside a custom hook. This allows you to reuse data-fetching logic across your application and provide a cleaner API to your components.
  9. Strategies for prefetching and preloading data with SWR

    main

    This example demonstrates four distinct patterns to prefetch data so that it is available for SWR to use immediately when a user navigates or interacts with the UI. Combining these strategies can significantly improve perceived performance and user experience.

    1. HTML Link Preload: Use <link rel="preload"> in your HTML to instruct the browser to fetch data while the initial page is rendering.
    2. External Fetch & Mutate: In a browser environment, execute the fetch and SWR mutate calls outside of the React component lifecycle.
    3. React Effect Prefetching: Use a React useEffect hook to trigger a fetch and mutate for the next expected page's data after the current component has rendered.
    4. Interaction-based Prefetching: Trigger a fetch and mutate for the next page's data when a user performs an action, such as moving their mouse over a link (hovering).
  10. Deploy the SWR Suspense example to Vercel

    main

    You can deploy your own instance of the SWR Suspense example directly to Vercel using the one-click deploy button.

    [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?s=https://github.com/vercel/swr/tree/main/examples/suspense)
  11. Download and run the Storage Tab Sync example

    main

    To run this specific example locally, download the source code from the SWR repository, navigate to the directory, and start the development server using your preferred package manager.

    # Download the example
    curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/storage-tab-sync
    cd storage-tab-sync
    
    # Install dependencies and run
    yarn
    yarn dev
    # or
    npm install
    npm run dev
  12. Download and run the local-state-sharing example

    main

    To explore how to share local state between React components using SWR, you can download the example directly from the SWR repository, install its dependencies, and start the development server.

    # Download the example
    curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/local-state-sharing
    cd local-state-sharing
    
    # Install and run using yarn
    yarn
    yarn dev
    
    # OR install and run using npm
    npm install
    npm run dev