Static and Dynamic Rendering
Overview
Static and dynamic rendering are two approaches to generating HTML for web pages. Static rendering generates HTML at build time, while dynamic rendering generates HTML at runtime. Data requests create an unintentional waterfall. Data updates in a static page require a full rebuild before updates are visible.
Prepare
This activity will help you understand the differences between static and dynamic rendering in Next.js and when to use each approach.
Static Rendering
Static rendering generates HTML at build time. This means the HTML is generated when the application is built, not when it is requested by a user. When a user visits a static page, they receive the cached result, pre-generated HTML. The benefits of static rendering include:
- Faster load times for users because the HTML is pre-generated and cached. Users around the world can access the cached content quickly.
- There is a reduced server load and thus can reduce computational costs.
- Improved SEO performance due to pre-generated HTML content given that the content is much easier to index. Typically page rankings improve.
Static rendering is useful for content that doesn't change frequently and can be pre-rendered.
Dynamic Rendering
Dynamic rendering generates HTML at runtime. This means the HTML is generated when the application is requested by a user. The benefits of dynamic rendering include:
- Real-time updates for users because the HTML is generated on-demand. This is ideal on applications where content changes frequently.
- Personalized content for each user based on their preferences and interactions.
- Request Time Information is information that can only be available at the time of the request, such as cookies or the URL search parameters.
Dynamic rendering is useful for content that changes frequently or is personalized for each user.
With dynamic rendering, your application is only as fast as the slowest data source it depends on.
Activity Instructions
In your portfolio application, you have been using static rendering to display your projects. In this activity, you will update your application to use dynamic rendering instead. This will allow you to fetch the latest project data from your database each time a user visits the page.
Follow these steps to update your portfolio application to use dynamic rendering:
- Open the page component that displays your projects (For example,
app/projects/page.tsx). - Replace the static data fetching method (For example,
getStaticProps) with a dynamic data fetching method (For example,getServerSidePropsor fetch directly in the component). - Update the component to fetch project data from your database instead of using static data.
- Test your application to ensure that it correctly fetches and displays the latest project data each time you refresh the page.