No Justice. No Peace. #BlackLivesMatter

Blog:Remote Data Fetching w/SWR

Manny Becerra as a child

January 2020

Build a fast and reactive UI

The rollout of React Hooks the other year was a big, next step in reducing the friction in the creation of reactive user interfaces and experiences. Hooks allows developers to separate logic and concerns a bit further and move more toward functional programming and away from classes.

Recently, the team over at Next.js, created a custom hook of their own dubbed, useSwr; which, stands for stale-while-revalidate. According to the docs, With SWR, components will get a stream of data updates constantly and automatically. And the UI will be always fast and reactive.

How to use the SWR hook

useSWR is pretty cool and straightforward to leverage. To get started, you can do something like the following example which is contrived, yet common enough:

import useSWR from 'swr'
import { Container, Paragraph } from '@/components/system'

function Dashboard() {
  const { data: user, error: userError } = useSWR('/api/user', fetcher)
  const { data: dashboard, error: dashboardError } = useSWR('/api/dashboard', fetcher)
  if (userError || dashboardError) return <Container>failed to load</Container>
  if (!user && !dashboard) return <Container>loading...</Container>
  return (
    <Container>
      <Paragraph>Hey there {user.name}!</Paragraph>
    </Container>
    //... render dashboard data
  )
}

Unpacking the sample code

In our above example, there are two useSWR hook instances, and each returns two values: data and error. When the request (fetcher) is not yet finished, data will be undefined. And when we get a response, it sets data and error based on the result of fetcher and rerenders the component. The fetcher prop passed into useSWR can be any asynchronous function, so you can use your preferred data-fetching library to handle that part, like fetch, axios, etc.


I've already played around with SWR and implemented it in a project, particularly for user authentication and keeping a dashboard syncronized with an API data source. You can see a simple demo of SWR in the starter kit I created, or the various examples provided by the useSWR team.

Learn more about useSWR at https://swr.now.sh.

Manny


I am human, a father, and a problem solver: a tech and people leader with a passion and proven track-record in building and leading compassionate, productive teams—remote and on-site—within a continuous learning culture. My teams and I champion usable, inclusive digital products and online experiences. My work, passion and intentions also intersect with advising small businesses and political campaigns, life-long learning, outdoor advocacy, community building, and uplifting others. Learn more about Manny