0
votes

I'm learning NextJS and am trying to wrap my head around the difference between server-rendered and client-side React code -- while NextJS seems great, I'm having some trouble conceptually understanding the difference between the two types of rendering and what those differences mean.

For instance, I came across the following comment in the NextJS documentation, in the section describing `_document``

// _document is only rendered on the server side and not on the client side
// Event handlers like onClick can't be added to this file

Why can one not put event handlers in _document? What is the difference between this and putting them 'client side'?

Also I'm somewhat confused because NextJS seems to be oriented around building 'pages' -- that is, there's support for adding <HEADER>, etc, as if we were building a static website. But if I were to build a React SPA, there's only one page, no? One can simulate different 'pages' using the React router, but the actual containing HTML (header, body, etc) remains the same, no? That is, we never really leave the actual HTML page?

I can use NextJS OK -- following through the documentation's tutorials -- but clearly conceptually I'm missing the forest for the trees. Any clues or pointers much appreciated!

1

1 Answers

3
votes

pages/_app.js is where you need to client-side codes. It is shared between all pages.

pages/_document.js only runs in SSR. so you need to put relevant code there.

Saying that, you only need to create these pages if you need to modify the normal behaviour of the app and customise it in your way.

SSR means Server side rendering and it happens when you type url in urlbar and press enter or when you refresh the page with refresh button.

CSR Client Side Rendering on the other hand is the way of SPA(single page app). so the URL change but there is no server call. It look for resources in pages directory for routing.

Next HEAD is way to manipulate the header tags like meta, title etc. in every page. It will give you freedom of customising head tag.