Installation

npm i swr

Overview

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 useSWR hook accepts a key string and a fetcher function. key is a unique identifier of the data (normally the API URL) and will be passed to fetcherfetcher can be any asynchronous function which returns the data, you can use the native fetch or tools like Axios.

The hook returns 3 values: dataisLoading and error, based on the status of the request.