Remote Data Fetching With React Hooks – swr

Author: zeit
Views Total: 28
Official Page: Go to website
License: MIT

SWR is a React Hooks library for remote data fetching.

Features:

  • Transport and protocol agnostic data fetching
  • Fast page navigation
  • Revalidation on focus
  • Interval polling
  • Request deduplication
  • Local mutation
  • Pagination
  • TypeScript ready
  • SSR support
  • Suspense mode
  • React Native support
  • Minimal API
  • And more

Installation:

# Yarn
$ yarn add swr

# NPM
$ npm install swr --save

Basic Usage:

Import modules.

import useSWR from 'swr';

Fetch data remotely. Possible parameters:

  • key: a function, string, array for the request
  • fetcher:  a Promise returning function to fetch your data
  • options: optional settings
const { data, error, isValidating, mutate } = useSWR(key, fetcher, options)

Possible options and event handlers:

ConfigInterface = {
  // events
  onLoadingSlow: () => {},
  onSuccess: () => {},
  onError: () => {},
  onErrorRetry,
  errorRetryInterval: (slowConnection ? 10 : 5) * 1000,
  focusThrottleInterval: 5 * 1000,
  dedupingInterval: 2 * 1000,
  loadingTimeout: (slowConnection ? 5 : 3) * 1000,
  refreshInterval: 0,
  revalidateOnFocus: true,
  revalidateOnReconnect: true,
  refreshWhenHidden: false,
  refreshWhenOffline: false,
  shouldRetryOnError: true,
  suspense: false,
  compare: deepEqual
}

Preview:

Remote Data Fetching With React Hooks - swr