DEV Community

devneagu
devneagu

Posted on

Use NextJS Server Side Pre-Rendering like a boss !πŸ”₯

So you want to get better at pre-rendering your components ? You've come in the right place!

The main power of NextJS regarding the SSG is pre-rendering, building fast and having a good dev experience.

Why should I pre-render?

Pre-rendering comes with a better user experience, faster page loads and a better dev experience.

Image description
(source : Vercel)

The purpose of pre-rendering is to paint the macro components of your page. We are interested in putting the buttons, menus and sections with or without content.

The second step is to obtain the data via getStaticProps from an API or CMS (you can use Strapi, Contentful, Sanity and so on).

Keep in mind, at micro level, we want to nest our data inside the macro components without canceling the pre-rendering, if we compare using front-end react hooks that need a browser, we will cancel the pre-rendering feature and we'll build the component at runtime on the user browser.

Lower the dependencies of browser only react hooks.

If you have components that require browser characteristics, you'll need to add complex logic, failing to pre-render the component. In some cases, this is a good thing in some cases analyse if you really need that hook. This applies to useEffect logic as well.

What should I pre-render if the component is client only?

For a good user experience, you have two options : loading or skeleton component. The skeleton component have been researched as a better candidate because it tricks your mind that the component is rendering fast.

What should we pre-render if we have complex desktop, tablet and mobile page components?

You can use nextJS middleware and check the user-agent :

  • We'll filter by using the user-agent request and we'll match the screen layout with our page.

For example, you can have a mobile page, a desktop page and a tablet page (e.g. homepage-mobile.tsx, homepage-desktop.tsx). You'll select the page needed and change the response accordingly.

How to test how your page is pre-rendered?

Build your project and disable the javascript on your page. You will see how the page first renders with the pre-rendering feature.

Top comments (0)