Turning NextJS into CRA (don't actually do this)
Spin up a new Create React App and take a look at the DOM.
What do you see? Look at the elements tab. Your DOM is populated with the various html tags making up your application’s components.
Now look at the network tab. First resource in the waterfall is your html doc. Take a look at this doc’s response. You will see something like:
<body>
<div id="root"></div>
</body>
This is the essence of client-side rendering. Create React App relies on browser functionality to create all of the DOM elements at runtime.
Now spin up a new NextJS app and look at the DOM.
You will roughly see the same thing in the elements tab as you saw with CRA.
Again, look at the network tab. Check out the response of the html doc. All of the DOM elements have already been generated.
<body>
<div id="root"><h1>My Cool App</h1><article><h2>Hi</h2><p>Hello World</p></article></div>
</body>
This is the essence of server-side-rendering. We are letting the server (in this case Node) create the DOM elements at runtime, stick them in the HTML, and then they are already there when the browser runs the initial network call for the html doc.
If we want to, we can override how NextJS handles this ahead-of-time code generation.
By default, NextJS recognizes any components created and default-exported within the ’pages’ folder as a default page of your app to be server-side rendered.
If we rip out the functionality from one of these ’pages’ and place it in its own component file, then use Next Dynamic to import that file in our index file...
import dynamic from ’next/dynamic’;
const LazyHomeComponent = dynamic(() => import("../components/home"), { ssr: false });
export default function Home() { return <LazyHomeComponent /> }
...and now spin it up and take a look at the html response again.
The html response once again has an empty div and the core component functionality will be client-side generated at runtime.
We have now created CRA within NextJS.
When might this actually be useful?
If you have library/package imports that need to run on the client but cannot run on the server.