FRAMEWORK » REACT » PLUGINS

SWR

Usage

Install the swr package.

javascript
import useSWR from 'swr';
import useSWRImmutable from 'swr/immutable';

// If data can change
const dataQuery = useSWR(key, fetcher, options);

// If data is expected to NOT change
const dataQuery = useSWRImmutable(key, fetcher, options);

key can be anything (string, array, dict), it will be passed as argument to fetcher.

fetcher is a function or an async function. It receives key as argument.

options is a dict of configuration options:

OptionDescription
keepPreviousDataReturn the previous key's data until the new data has been loaded.
refreshIntervalPolling interval in milliseconds (0 to disable).
revalidateOnFocusAutomatically revalidate when window gets focused.
shouldRetryOnErrorRetry when fetcher has an error.
onErrorCallback function when a request returns an error.
onSuccessCallback function when a request finishes successfully.

The result:

javascript
const { data, error, isLoading, isValidating, mutate } = dataQuery;

Typescript

Detailed documentation here.

Explicitly specify the types for key and fetcher's arguments:

typescript
import useSWR, { Fetcher } from 'swr';
 
const uid = 'user_id';
const fetcher: Fetcher<User, string> = (id) => getUserById(id);
      //     data type ^     ^ argument type
 
const { data } = useSWR(uid, fetcher);
// `data` is `User | undefined`

Explicitly specify the types of data and error, respectively:

typescript
const { data, error } = useSWR<User, Error>(uid, fetcher);
// `data` is `User | undefined`
// `error` is `Error | undefined`