Next.js: what is the difference between using the "revalidate" option in the getStaticProps and using the SWR package?

Viewed 833

Next.js has this "revalidate" option out of the box:

export async function getStaticProps(context) {
  const data = await getData();

  if (!data) {
    return {
      notFound: true,
    };
  }

  return {
    props: { data },
    revalidate: 60,
  }
}

The above code will make sure that a page is regenerated after 60 seconds from the moment we requested the updated data (first refresh to make a request for the new data, second refresh to update page). This is based on the Incremental Static Regeneration, so the site doesn't need to be rebuilt.

From the SWR docs:

If your page contains frequently updating data, and you don’t need to pre-render the data, SWR is a perfect fit and no special setup needed: just import useSWR and use the hook inside any components that use the data.

So, does it mean that in this case, useSWR is basically the same as the next.js "revalidate" option? It seems to be doing the same thing but how often does the revalidation occur then? Is there any advantage to using one over the other?

1 Answers

No, they are not the same and fit different use-cases.

useSWR is a data fetching hook that provides caching and automatic revalidation mechanisms (which you can control) to keep the data fresh on the client-side. The data revalidation will happen on the client and will only benefit that single user.

Using revalidate and Incremental Static Regeneration allows you to regenerate static pages on the server-side. The entire page gets generated again on the server and is statically cached. Any subsequent requests (from any user) will be served the regenerated page.

Using one or the other depends entirely on your requirements, and they're not mutually exclusive - you can use both at the same time.

Related