SPA do all the work client-side, in particular the rendering. The client downloads a shell page and a JavaScript bundle which takes care of rendering.
JavaScript can also be run server-side. Why don't we run React there too to directly have HTML?
The JavaScript code is executed by the browser (e.g. V8, Spider Monkey) to generate DOM nodes.
The JavaScript code is executed by the server (e.g. Node) to generate HTML, which is then sent to the client.
As JavaScript can be used on the client and on the server, React can run on Node, with the caveat that it does not have access to the DOM API. Instead, it returns an HTML string.
As much as possible, we should strive to offer both rendering strategies (CSR and SSR) and let the developer pick the right one. Client-side code should always have an SSR fallback.
For this course, we shall use Next.js, which is a meta-framework allowing you to write React code to be rendered on the client or the server.
Next uses file-based routing.
Layouts allow you to wrap your page into a component (e.g. to add a navbar). They can be put in app/[route]/layout.tsx
. Layout apply to subroutes.
Next.js handles the routing on client if possible and fallsback to server-side routing.
A server component in React is a component which will be transformed by React on the server into an HTML string.
useState
or useEffect
In Next.js, components are server components by default. Client components (i.e. what you have done so far) need 'use client'
at the top of the file.
Client components cross the network boundary and can only have client components inside them
npx create-next-app@latest
Use the Next.js documentation.