Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

swr

Package Overview
Dependencies
Maintainers
8
Versions
162
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

swr

React Hooks library for remote data fetching

  • 2.2.5
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.4M
increased by7.15%
Maintainers
8
Weekly downloads
 
Created

What is swr?

The swr npm package is a React Hooks library for remote data fetching. The name 'SWR' is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.

What are swr's main functionalities?

Data Fetching

SWR provides a hook called useSWR for data fetching. You can pass a key and a fetcher function, and it will return the data, error, and other useful values for handling the UI state.

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>
}

Automatic Revalidation

SWR automatically revalidates data when a user focuses on the window or when the network is reconnected. It can also be configured to revalidate data at a fixed interval.

import useSWR from 'swr'

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

  // data will be revalidated every 3 seconds
  return <div>{data.name}</div>
}

Local Mutation

SWR allows you to mutate the local data immediately and revalidate it in the background. This provides an optimistic UI update experience.

import useSWR, { mutate } from 'swr'

function updateUsername(name) {
  mutate('/api/user', { ...data, name }, false)
  fetch('/api/user', {
    method: 'POST',
    body: JSON.stringify({ name })
  }).then(() => {
    mutate('/api/user')
  })
}

Other packages similar to swr

Keywords

FAQs

Package last updated on 15 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc