'Does getStaticProps fetch data every time I get back same page?

I am using routes to get page ex. page/[id].js and show data for that id only. So will it refetch data every time I visit this page? ex. going to the next page through a link on this page and pressed back to get back to this page. Like it happens in React.js data fetching using DidComponentMount it fetches every time it mounts, even when you get back already visited the page.

export async function getStaticProps(context) {
    const res = await fetch(`https://.../data/${context.params.id}`)
    const data = await res.json()
    return {
        props: { data }
    }
}


Solution 1:[1]

getStaticProps inside our pages (not inside components) tells next.js that current page will be statically generated. The code executed in getStaticProps will not be included in the code bundle that sent back to the client.

The idea of getStatisProps you pre-generate the page during build time. That means all the HTML code and data are prepared in advance. Since pages are prebuilt, when we deploy them they can get cached by the server so incoming requests can be served instantly. So when pages are served, they are not empty, they are pre-populated with content.

if you run npm run build, visit .next/server/ directory and you will see the pre-generated HTML files.

What happens if data changes frequently. pre-generated pages are great if you are building something fully static. If you are rendering a blog post whose data does not change, it is a good idea to pre-generate the page.

Each time you add new data to your statically generated page, in order to see the change, you have to rebuild your project again. But next.js solves this with incremental static generation. With this, your page continuously gets updated without redeploying your app. You just tell next.js that you want your page to get pre-generated after each request at most x seconds. Regenerated page will replace the old page. So you can have ongoing pregenerating for incoming requests. To do so, you just add revalidate property:

export async function getStaticProps(context) {
      const res = await fetch(`https://.../data/${context.params.id}`)
      const data = await res.json()
      return {
        props: { data }
      },
      // time in seconds
      // this tells if last generated page was more than 60 seconds ago, pregenerate it
      revalidate: 60
    }

If you do not add revalidate property, your prebuild HTML page will be served from the cache

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yilmaz