Course
CSR
Next.js Mastery: From Fundamentals to Full-Stack
Unlock the power of Next.js with this comprehensive course! Starting with the basics, you’ll learn essential skills such as routing, data fetching, and styling. Progress through practical projects, including building your own React Notes app, to gain hands-on experience. Dive into the source code to understand the inner workings and core principles of Next.js. Perfect for developers with a basic knowledge of React and Node.js, this course ensures you’ll be ready to create high-performance full-stack applications efficiently. Join us and master Next.js, backed by industry experts and a supportive learning community.
Introduction
Previously, learning Next.js might have been motivated by hearing that a single framework could implement CSR, SSR, SSG, and ISR functionalities. However, after Next.js v13, Next.js introduced the App Router based on React Server Components.
Terms like SSR and SSG have been de-emphasized and are less frequently mentioned in the latest documentation (although these features are still available). Nevertheless, understanding the principles and differences behind these terms remains helpful for understanding and using Next.js.
CSR (Client-Side Rendering)
Concept Introduction
Let's start with conventional CSR.
CSR stands for "Client-side Rendering". As the name suggests, the rendering work is mainly performed on the client side.
The conventional way of using React is client-side rendering. The browser first downloads a very small HTML file and the required JavaScript files. Operations such as sending requests, fetching data, updating the DOM, and rendering the page are executed in JavaScript.
The biggest problem with this approach is that it's not fast enough. (SEO issues are secondary, as modern crawlers generally support CSR-rendered pages now.)
The page won't be fully presented until the JavaScript is downloaded, parsed, executed, and the data request has returned.
Implementing CSR
Next.js supports CSR. In the Next.js Pages Router, there are two ways to implement client-side rendering.
One way is to use the React
useEffect
hook in the page, instead of server-side rendering methods (such as getStaticProps
and getServerSideProps
, which we'll discuss later). Here's an example:// pages/csr.jsimport React, { useState, useEffect } from 'react'
export default function Page() { const [data, setData] = useState(null)
useEffect(() => { const fetchData = async () => { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1') if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`) } const result = await response.json() setData(result) }
fetchData().catch((e) => { console.error('An error occurred while fetching the data: ', e) }) }, [])
return <p>{data ? `Your data: ${JSON.stringify(data)}` : 'Loading...'}</p>}
As you can see, the request is sent from the client, and the page displays a loading state. After the data returns, the main content is rendered on the client side.
When visiting
/csr
, the rendered HTML file will be:<body> <div id="__next"> <p>Loading...</p> </div> ...
After JavaScript obtains the data, it finally updates to:
<body monica-version="2.4.5" monica-id="ofpnmcalabcbjgholdjcjblkibolbppb"> <div id="__next">
<p>Your data: {"userId":1,“id":1,"title":"delectus aut autem","completed":false}</p> </div> ...
The second method is to use a data fetching library on the client side, such as SWR (also developed by the Next.js team) or TanStack Query. Here's an example:
// pages/csr2.jsimport useSWR from 'swr'
const fetcher = (...args) => fetch(...args).then((res) => res.json())
export default function Page() { const { data, error, isLoading } = useSWR('https://jsonplaceholder.typicode.com/todos/1', fetcher)
if (error) return <p>Failed to load.</p> if (isLoading) return <p>Loading...</p> return <p>Your Data: {data.title}</p>}
The effect is the same as the previous example.