Convert Figma logo to code with AI

vercel logoswr

React Hooks for Data Fetching

30,395
1,214
30,395
136

Top Related Projects

42,139

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.

:rocket:  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.

46,119

🐻 Bear necessities for state management in React

The official, opinionated, batteries-included toolset for efficient Redux development

18,398

Relay is a JavaScript framework for building data-driven React applications.

Quick Overview

SWR (stale-while-revalidate) is a React Hooks library for data fetching. It provides a lightweight and efficient way to handle remote data fetching, caching, and state management in React applications. SWR focuses on delivering a great user experience by serving stale data first, then fetching and updating with fresh data.

Pros

  • Automatic caching and revalidation
  • Real-time data updates and optimistic UI
  • Built-in error handling and retry mechanism
  • Supports pagination and infinite loading

Cons

  • Learning curve for developers new to the SWR pattern
  • Potential over-fetching if not configured properly
  • Limited built-in support for complex data mutations
  • May require additional setup for server-side rendering

Code Examples

Fetching data with SWR:

import useSWR from 'swr'

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)

  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>
  return <div>Hello {data.name}!</div>
}

Conditional fetching:

function User({ id }) {
  const { data } = useSWR(id ? `/api/user/${id}` : null, fetcher)

  if (!data) return <div>Loading...</div>
  return <div>{data.name}</div>
}

Mutating data:

import useSWR, { mutate } from 'swr'

function Profile() {
  const { data } = useSWR('/api/user', fetcher)

  async function updateUser(newName) {
    await fetch('/api/user', { method: 'POST', body: newName })
    mutate('/api/user')
  }

  return (
    <div>
      <h1>My name is {data.name}.</h1>
      <button onClick={() => updateUser('new name')}>Update</button>
    </div>
  )
}

Getting Started

To start using SWR in your React project:

  1. Install SWR:

    npm install swr
    
  2. Import and use the useSWR hook in your component:

    import useSWR from 'swr'
    
    function MyComponent() {
      const { data, error } = useSWR('/api/data', fetcher)
    
      if (error) return <div>Error loading data</div>
      if (!data) return <div>Loading...</div>
      return <div>{data}</div>
    }
    
  3. Define a fetcher function (e.g., using fetch):

    const fetcher = (...args) => fetch(...args).then(res => res.json())
    
  4. Optionally, set up a global configuration:

    import { SWRConfig } from 'swr'
    
    function MyApp({ Component, pageProps }) {
      return (
        <SWRConfig value={{ fetcher }}>
          <Component {...pageProps} />
        </SWRConfig>
      )
    }
    

Competitor Comparisons

42,139

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.

Pros of Query

  • More robust and feature-rich, offering advanced capabilities like infinite queries and pagination
  • Better TypeScript support with stricter typing
  • Larger ecosystem with additional tools and plugins

Cons of Query

  • Steeper learning curve due to more complex API and concepts
  • Larger bundle size, which may impact performance in smaller applications
  • More verbose configuration and setup compared to SWR

Code Comparison

SWR:

import useSWR from 'swr'

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)
  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>
  return <div>Hello {data.name}!</div>
}

Query:

import { useQuery } from '@tanstack/react-query'

function Profile() {
  const { data, isLoading, error } = useQuery(['user'], fetchUser)
  if (error) return <div>Failed to load</div>
  if (isLoading) return <div>Loading...</div>
  return <div>Hello {data.name}!</div>
}

Both libraries provide similar core functionality for data fetching and caching, but Query offers more advanced features at the cost of increased complexity. SWR is simpler and easier to use for basic scenarios, while Query shines in larger applications with complex data requirements. The choice between them depends on the specific needs of your project and your team's preferences.

:rocket:  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.

Pros of Apollo Client

  • Comprehensive GraphQL solution with advanced features like caching, optimistic UI, and subscriptions
  • Robust ecosystem with tools for state management, developer experience, and testing
  • Seamless integration with Apollo Server and other GraphQL backends

Cons of Apollo Client

  • Steeper learning curve due to its extensive feature set
  • Larger bundle size compared to SWR's lightweight approach
  • More complex setup and configuration for simple use cases

Code Comparison

Apollo Client:

const { loading, error, data } = useQuery(GET_DOGS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return data.dogs.map(({ id, breed }) => (
  <p key={id}>{breed}</p>
));

SWR:

const { data, error } = useSWR('/api/dogs', fetcher);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return data.map(({ id, breed }) => (
  <p key={id}>{breed}</p>
));

Both libraries provide similar functionality for data fetching and rendering, but Apollo Client's code is more GraphQL-specific, while SWR offers a more generic approach that can be used with various data sources. Apollo Client requires more setup for GraphQL operations, whereas SWR's usage is more straightforward for simple REST API calls.

46,119

🐻 Bear necessities for state management in React

Pros of Zustand

  • Simpler API with less boilerplate code
  • More flexible state management, not limited to data fetching
  • Smaller bundle size and better performance

Cons of Zustand

  • Less opinionated, requiring more manual setup for complex scenarios
  • Fewer built-in features for data fetching and caching
  • Less automatic optimizations for server-side rendering

Code Comparison

Zustand:

import create from 'zustand'

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}))

SWR:

import useSWR from 'swr'

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)
  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}

Summary

Zustand is a lightweight and flexible state management solution, while SWR focuses on data fetching and caching. Zustand offers more freedom in state management but requires more manual setup. SWR provides powerful data fetching capabilities out of the box but is more specialized. Choose Zustand for general state management needs and SWR for optimized data fetching and caching in React applications.

The official, opinionated, batteries-included toolset for efficient Redux development

Pros of Redux Toolkit

  • Provides a standardized way to write Redux logic, reducing boilerplate code
  • Includes utilities for common Redux use cases, like creating slices and async thunks
  • Offers better performance optimization through built-in memoization techniques

Cons of Redux Toolkit

  • Steeper learning curve for developers new to Redux concepts
  • Can be overkill for smaller applications with simple state management needs
  • Requires more setup and configuration compared to SWR's simpler API

Code Comparison

Redux Toolkit:

import { createSlice, configureStore } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: state => state + 1,
  },
})

const store = configureStore({
  reducer: counterSlice.reducer,
})

SWR:

import useSWR from 'swr'

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)

  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>
  return <div>Hello {data.name}!</div>
}

Redux Toolkit is more suited for complex state management scenarios, while SWR excels in data fetching and caching for React applications. The choice between them depends on the specific needs of your project.

18,398

Relay is a JavaScript framework for building data-driven React applications.

Pros of Relay

  • Optimized for large-scale applications with complex data requirements
  • Powerful declarative data fetching with colocation of queries
  • Strong type safety and compile-time checks

Cons of Relay

  • Steeper learning curve and more complex setup
  • Requires GraphQL backend
  • Less flexible for simple use cases or REST APIs

Code Comparison

Relay:

const RepositoryNameRenderer = createFragmentContainer(
  ({ repository }) => <div>{repository.name}</div>,
  graphql`
    fragment RepositoryNameRenderer_repository on Repository {
      name
    }
  `
);

SWR:

const { data, error } = useSWR('/api/repository', fetcher)

return <div>{data ? data.name : 'Loading...'}</div>

Key Differences

  • Relay is tightly integrated with GraphQL, while SWR is more flexible and works with any data fetching method
  • Relay requires more setup and configuration, whereas SWR is simpler to get started with
  • Relay offers more advanced features for complex data management, while SWR focuses on simplicity and ease of use

Both libraries have their strengths, with Relay excelling in large, complex applications and SWR offering a more lightweight solution for simpler use cases.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

SWR


Introduction

SWR is a React Hooks library for data fetching.

The name “SWR” is derived from stale-while-revalidate, a cache invalidation strategy popularized by HTTP RFC 5861. SWR first returns the data from cache (stale), then sends the request (revalidate), and finally comes with the up-to-date data again.

With just one hook, you can significantly simplify the data fetching logic in your project. And it also covered in all aspects of speed, correctness, and stability to help you build better experiences:

  • Fast, lightweight and reusable data fetching
  • Transport and protocol agnostic
  • Built-in cache and request deduplication
  • Real-time experience
  • Revalidation on focus
  • Revalidation on network recovery
  • Polling
  • Pagination and scroll position recovery
  • SSR and SSG
  • Local mutation (Optimistic UI)
  • Built-in smart error retry
  • TypeScript
  • React Suspense
  • React Native

...and a lot more.

With SWR, components will get a stream of data updates constantly and automatically. Thus, the UI will be always fast and reactive.


View full documentation and examples on swr.vercel.app.


Quick Start

import useSWR from 'swr'

function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)

  if (error) return <div>failed to load</div>
  if (isLoading) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}

In this example, the React Hook useSWR accepts a key and a fetcher function. The key is a unique identifier of the request, normally the URL of the API. And the fetcher accepts key as its parameter and returns the data asynchronously.

useSWR also returns 3 values: data, isLoading and error. When the request (fetcher) is not yet finished, data will be undefined and isLoading will be true. When we get a response, it sets data and error based on the result of fetcher, isLoading to false and rerenders the component.

Note that fetcher can be any asynchronous function, you can use your favourite data-fetching library to handle that part.


View full documentation and examples on swr.vercel.app.


Authors

This library is created by the team behind Next.js, with contributions from our community:

Contributors

Thanks to Ryan Chen for providing the awesome swr npm package name!


License

The MIT License.

NPM DownloadsLast 30 Days