Prerendering

Before data-fetching, we must understand another fundamental concept: pre-rendering. Each page in Next.js is pre-rendered, meaning the html is generated beforehand. Next.js uses a process called hydration, where during the initial page load, Next.js sends down pre-rendered HTML along with the necessary JavaScript bundle specific to that page. Once the page is loaded, the javascript is executed and makes the page interactive–the act of hydration.

Next.js supports two types of pre-rendering:

  1. Static Generation (SSG):
  2. Server-side Rendering (SSR):

We can choose which pre-rendering method to use for each page using route handlers to fetch data like getStaticProps (for Static Generation) or getServerSideProps (for Server-side Rendering). Most pages tend to use static generation, as it is much faster than rendering the page at every request, except when page content must change with every request such as a world clock. Pages that do not require external data are automatically rendered statically.

Static and Dynamic Generation

To specify static generation while importing data from an external source, export an asynchronous function called getStaticProps. This will run at build-time and we can then retrieve external data to send to the page:

Untitled

To specify dynamic generation, export an async function named getServerSideProps from the page file:

Untitled

Client-side Rendering

Finally, to prevent pre-rendering, we can use client-side rendering. This pre-renders the parts of the page for which external data is required, then external data is retrieved and added while the page loads. This can be done by defining an initiate state, setting up an event handler/ function to trigger the rendering, then using the useState hook to manage the state of the component. As covered in the React JS chapter, this can be done as follows:

Untitled

Dynamic URLs

In addition to generating page content dependent on external data, we can also generate page paths dependent on external data. This is known as using dynamic URLs. We can statically generate pages with the following method:

Untitled