Skip to content

API Options

const { data, error, isValidating, mutate } = useSWR(key, fetcher, options)

Parameters

  • key: a unique key string for the request (or a function / array / null) (advanced usage)
  • fetcher: (optional) a Promise returning function to fetch your data (details)
  • options: (optional) an object of options for this SWR hook

Return Values

  • data: data for the given key resolved by fetcher (or undefined if not loaded)
  • error: error thrown by fetcher (or undefined)
  • isValidating: if there's a request or revalidation loading
  • mutate(data?, shouldRevalidate?): function to mutate the cached data

Options

  • suspense = false: enable React Suspense mode (details)
  • fetcher = window.fetch(url).then(res => res.json()): the fetcher function
  • initialData: initial data to be returned (note: This is per-hook) (details)
  • revalidateOnMount: enable or disable automatic revalidation when component is mounted (by default revalidation occurs on mount when initialData is not set, use this flag to force behavior)
  • revalidateOnFocus = true: auto revalidate when window gets focused (details)
  • revalidateOnReconnect = true: automatically revalidate when the browser regains a network connection (via navigator.onLine) (details)
  • refreshInterval = 0: polling interval (disabled by default) (details)
  • refreshWhenHidden = false: polling when the window is invisible (if refreshInterval is enabled)
  • refreshWhenOffline = false: polling when the browser is offline (determined by navigator.onLine)
  • shouldRetryOnError = true: retry when fetcher has an error
  • dedupingInterval = 2000: dedupe requests with the same key in this time span
  • focusThrottleInterval = 5000: only revalidate once during a time span
  • loadingTimeout = 3000: timeout to trigger the onLoadingSlow event
  • errorRetryInterval = 5000: error retry interval
  • errorRetryCount: max error retry count
  • onLoadingSlow(key, config): callback function when a request takes too long to load (see loadingTimeout)
  • onSuccess(data, key, config): callback function when a request finishes successfully
  • onError(err, key, config): callback function when a request returns an error
  • onErrorRetry(err, key, config, revalidate, revalidateOps): handler for error retry
  • compare(a, b): comparison function used to detect when returned data has changed, to avoid spurious rerenders. By default, dequal is used.

💡

When under a slow network (2G, <= 70Kbps), errorRetryInterval will be 10s, and loadingTimeout will be 5s by default.

You can also use global configuration to provide default options.