Combining client side and server side rendering on same page using next.js

Tram Ho

We can easily create Client rendered pages (CSR) and Static generated pages (SG) using Next.js. But, often times, you’ll want your page to use a combination of those different rendering methods. Like, you want your static page to be generated with some data from api, then once the users browser has hydrated the static page, you want CSR to kick in. There is one way we can use this, by using the excellent SWR plugin from Vercel (`creators of Next.js). Let’s have a quick look about it in this article.

First, let’s create a next app by running

Now we need to create a mock api to serve us articles/posts.
Let’s create a new file in pages/posts.js and paste in

Now, we’ll install the SWR plugin

And create our blog component and also import the useSWR hook from the plugin we just installed

Now, let’s render the blog posts using the useSWR hook

Now let’s create the static generated file for our page, for this we’ll modify our code like

Let’s generate the page. For that run

You’ll see this after it’s successfully built

Note, the if we keep adding posts to our mock api while our blog is running, the data doesn’t get refreshed. We need to reload the page to do that

Let’s fix that now. For that, we will pass the revalidateOnMount option in our useSWR hook
So, the final code will be

Let’s check

Source code

https://github.com/Salekin-1169/blog-swr-demo

Learning Material

The official docs (obviously)

 

Share the news now

Source : Viblo