React Hooks for Remote Data Fetching

Go to official docs

  1. With SWR, components will get a stream of data updates constantly and automatically.
  2. useSWR accepts a key and a fetcher function.
  3. key is a unique identifier of the data, normally the URL of the API.
  4. Then key will be passed to fetcher, which can be any asynchronous function which returns the data.
  5. fetcher can be any asynchronous function, so you can use your favourite data-fetching library to handle that part.
  6. Or use GraphQL.
  7. useSWR returns 2 values: data and error, based on the status of the request.
  8. When the request (fetcher) is not yet finished, data will be undefined.
  9. And when we get a response, it sets data and error based on the result of fetcher and rerenders the component.
  10. The context SWRConfig can provide global configurations for all SWR hooks.
  11. For example, we can define a default fetcher.
  12. There are many options, these are just a few.
  13. You can always override options for specific hook calls.
  14. You can enable the suspense option to use SWR with React Suspense.
  15. In Suspense mode, data is always the fetch response (so you don't need to check if it's undefined). But if an error occurred, you need to use an error boundary to catch it.