πŸ–οΈ
Developer Note
  • Welcome
  • Git
    • Eslint & Prettier & Stylelint & Husky
  • Programming Language
    • JavaScript
      • Script Async vs Defer
      • Module
      • Const VS Let VS Var
      • Promise
      • Event Loop
      • Execution Context
      • Hoisting
      • Closure
      • Event Buddling and Capturing
      • Garbage Collection
      • This
      • Routing
      • Debounce and Throttle
      • Web Component
      • Iterator
      • Syntax
      • String
      • Array
      • Object
      • Proxy & Reflect
      • ProtoType
      • Class
      • Immutability
      • Typeof & Instanceof
      • Npm (Node package manager)
    • TypeScript
      • Utility Type
      • Type vs Interface
      • Any vs Unknown vs Never
      • Void and undefined
      • Strict Mode
      • Namespace
      • Enum
      • Module
      • Generic
    • Python
      • Local Development
      • Uv
      • Asyncio & Event loop
      • Context Manager
      • Iterator & Generator
      • Fast API
      • Pydantic & Data Class
    • Java
      • Compilation and Execution
      • Data Type
      • Enumeration
      • Data Structure
      • Try Catch
      • InputStream and OutputStream
      • Concurrent
      • Unicode Block
      • Build Tools
      • Servlet
      • Java 8
  • Coding Pattern
    • MVC vs MVVM
    • OOP vs Functional
    • Error Handling
    • MVC vs Flux
    • Imperative vs Declarative
    • Design Pattern
  • Web Communication
    • REST API
      • Web Hook
      • CORS issue
    • HTTPS
    • GraphQL
      • REST API vs GraphQL
      • Implementation (NodeJS + React)
    • Server-Sent Event
    • Web Socket
    • IP
    • Domain Name System (DNS)
  • Frontend
    • Progressive Web App (PWA)
    • Single Page & Multiple Page Application
    • Search Engine Optimiaztion (SEO)
    • Web bundling & Micro-frontend
      • Webpack
        • Using Webpack to build React Application
        • Using Webpack to build react library
      • Vite
      • Using rollup to build react library
      • Implementing micro frontend
    • Web Security
      • CSRF & Nonce
      • XSS
      • Click hijacking
    • Cypress
    • CSS
      • Core
        • Box Model
        • Inline vs Block
        • Flexbox & Grid
        • Pseudo Class
        • Position
      • Tailwind CSS
        • Shadcn
      • CSS In JS
        • Material UI
    • React
      • Core
        • Component Pattern
        • React Lazy & Suspense
        • React Portal
        • Error Boundary
        • Rendering Methods
        • Environment Variable
        • Conditional CSS
        • Memo
        • Forward Reference
        • High Order Component (HOC) & Custom Hook
        • TypeScript
      • State Management
        • Redux
        • Recoil
        • Zustand
      • Routing
        • React Router Dom
      • Data Fetching
        • Axios & Hook
        • React Query
        • Orval
      • Table
        • React Table
      • Form & Validation
        • React Hook Form
        • Zod
      • NextJS
        • Page Router
        • App Router
      • React Native
    • Angular
    • Svelte
      • Svelte Kit
  • Backend
    • Cache
      • Browser Cache
      • Web Browser Storage
      • Proxy
      • Redis
    • Rate limit
    • Monitoring
      • Logging
      • Distributed Tracing
    • Load Test
    • Encryption
    • Authentication
      • Password Protection
      • Cookie & Session
      • JSON Web Token
      • SSO
        • OAuth 2.0
        • OpenID Connect (OIDC)
        • SAML
    • Payment
      • Pre-built
      • Custom
    • File Handling
      • Upload & Download (Front-end)
      • Stream & Buffer
    • Microservice
      • API Gateway
      • Service Discovery
      • Load Balancer
      • Circuit Breaker
      • Message Broker
      • BulkHead & Zipkin
    • Elastic Search
    • Database
      • SQL
        • Group By vs Distinct
        • Index
        • N + 1 problem
        • Normalization
        • Foreign Key
        • Relationship
        • Union & Join
        • User Defined Type
      • NOSQL (MongoDB)
      • Transaction
      • Sharding
      • Lock (Concurrency Control)
    • NodeJS
      • NodeJS vs Java Spring
      • ExpressJS
      • NestJS
        • Swagger
        • Class Validator & Validation Pipe
        • Passport (Authentication)
      • Path Module
      • Database Connection
        • Integrating with MYSQL
        • Sequalize
        • Integrating with MongoDB
        • Prisma
        • MikroORM
        • Mongoose
      • Streaming
      • Worker Thread
      • Passport JS
      • JSON Web Token
      • Socket IO
      • Bull MQ
      • Pino (Logging)
      • Yeoman
    • Spring
      • Spring MVC
      • Spring REST
      • Spring Actuator
      • Aspect Oriented Programming (AOP)
      • Controller Advice
      • Filter
      • Interceptor
      • Concurrent
      • Spring Security
      • Spring Boot
      • Spring Cloud
        • Resilience 4j
      • Quartz vs Spring Batch
      • JPA and Hibernate
      • HATEOS
      • Swagger
      • Unit Test (Java Spring)
      • Unit Test (Spring boot)
  • DevOp
    • Docker
    • Kubernetes
      • Helm
    • Nginx
    • File System
    • Cloud
      • AWS
        • EC2 (Virtual Machine)
        • Network
        • IAM
          • Role-Service Binding
        • Database
        • Route 53
        • S3
        • Message Queue
        • Application Service
        • Serverless Framework
        • Data Analysis
        • Machine Learning
        • Monitoring
        • Security
      • Azure
        • Identity
        • Compute Resource
        • Networking
        • Storage
        • Monitoring
      • Google Cloud
        • IAM
          • Workload Identity Federation
        • Compute Engine
        • VPC Network
        • Storage
        • Kubernetes Engine
        • App Engine
        • Cloud function
        • Cloud Run
        • Infra as Code
        • Pub/Sub
    • Deployment Strategy
    • Jenkins
    • Examples
      • Deploy NextJS on GCP
      • Deploy Spring on Azure
      • Deploy React on Azure
  • Domain Knowledge
    • Web 3
      • Blockchain
      • Cryptocurrency
    • AI
      • Prompt
      • Chain & Agent
      • LangChain
      • Chunking
      • Search
      • Side Products
Powered by GitBook
On this page
  • Client Side Rendering (CSR)
  • Explanation
  • Pros
  • Cons
  • Server Side Rendering (SSR)
  • Explanation
  • Pros
  • Cons
  • SSR in React
  • CSR vs SSR
  • CSR
  • SSR
  • Static Site Generation (SSG)
  • Explanation
  • SSG vs SSR
  • Server Component
  • Explanation
  • Flow
  • vs SSR
  • Conclusion
  • References

Was this helpful?

  1. Frontend
  2. React
  3. Core

Rendering Methods

PreviousError BoundaryNextEnvironment Variable

Last updated 5 months ago

Was this helpful?

Client Side Rendering (CSR)

Explanation

  • Initially, the page of the html is empty

  • Until the javascript finished download, the screen will be rendered based javascript code

  • Finally, the page becomes interactive

Pros

  • The user interactivity will be better, as the data fetched can be determined by user

  • Also, after loading, the page becomes interactive

  • It is better to fetch large amount of data, as the data can be fetched separately, but not once time finished

  • The loading of navigating the page will be faster

Cons

  • low SEO

  • The initial loading is slow, especially when the network is slow, as the javascript file need to be waited for downloading

Server Side Rendering (SSR)

Explanation

  • The html with content will be render in server

  • Therefore, the content page can be viewed at this moment, but still not interactive

  • After javascript file is downloaded, the page becomes interactive

Pros

  • The initial loading is faster, as not need to wait javascript file be downloaded

  • Better SEO

Cons

  • When the page is changed, the page content with html need to render again

  • Even the page is viewable, but still not interactive , which may affect the user experience

  • The structure will be more complex for react

  • If the page containing large amount of data, it will be nightmare to render the whole of the page in once time

  • If the user request is frequently made , it will slow down the rendering from server, as the page is rendered for each user request

SSR in React

  • Initially, the page will rendered from the server

  • After javascript finished downloading, the react application will be hydrated and turn it into single page application. So that, when the page is changed , the whole of the page do not be rendered from server comparing with traditional SSR like jsp, php

CSR vs SSR

CSR

  • Better for the page with large amount of data and high interactivity

SSR

  • Better for the static page or page with fewer data

Static Site Generation (SSG)

Explanation

  • The static page will be pre-rendered during build time

  • Therefore, the initial static page will be shown when user request comes in

SSG vs SSR

  • The page will be rendered in build time for SSG and the content is always the same

  • The page will be rendered in run time for SSR and the content in each rendering can be different for each user request

Server Component

Explanation

// Next.js fetch API in action
async function loadPosts() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
   /* 
   * Since this is a server component, the below message  
   * won't be displayed in the browser's dev console.
   */ 
  console.log("Server Component fetching");
  // return res.json();
  return ["this is server component"];
}

// Next.js will invalidate the cache when a
// request comes in, at most once every 60 seconds.
export const revalidate = 60

const ServerComponent = async () => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const posts:any[] = await loadPosts();
  return (
    <div className="post-list">
      Server Component
      {posts.map((post) => (
        <div key={post} className="post-listing">
          <p className="post-body">{post}</p>
        </div>
      ))}
    </div>
  );
};

export default ServerComponent;
  • React Server Components are always rendered on the server

  • If the props of server component is updated, the re-rendering will also be conducted on server-side

  • Since the logic and dependencies is on server side, it will reduce the bundle size of javascript downloaded on the browser

  • The on click, on change , ... and react hook cannot be used

  • Commonly used on the component that mainly for visualization but not interaction, e.g: to do list

  • It is not allowed to import a Server Component into a Client Component since client components are rendered after server components

  • But it is allowed to pass Server Components to Client Components as Props. Therefore, <ClientComponent> and <ServerComponent> are decoupled and can be rendered independently. In this case, the child <ServerComponent> can be rendered on the server, well before <ClientComponent> is rendered on the client.

wrong.tsx
'use client'
 
// You cannot import a Server Component into a Client Component.
import ServerComponent from './Server-Component'
 
export default function ClientComponent({
  children,
}: {
  children: React.ReactNode
}) {
  const [count, setCount] = useState(0)
 
  return (
    <>
      <button onClick={() => setCount(count + 1)}>{count}</button>
      <ServerComponent />
    </>
  )
}
correct.tsx
'use client'
 
import { useState } from 'react'
 
export default function ClientComponent({
  children,
}: {
  children: React.ReactNode
}) {
  const [count, setCount] = useState(0)
 
  return (
    <>
      <button onClick={() => setCount(count + 1)}>{count}</button>
      {children}
    </>
  )
}

Flow

  • the life of a page using RSC always starts at the server, in response to some API call to render a React component. This β€œroot” component is always a server component, which may render other server or client components

  • The end goal of server-side is to render the initial root server component into a tree of base html tags and client component β€œplaceholders” which contains the path of client component function to form a hybrid tree of server and client components. We can then serialize this tree, send it to the browser in JSON

  • The browser receives the JSON output from the server, and now must start reconstructing the React tree to be rendered in the browser to replace the client placeholder into real client component function

vs SSR

  • SSR apps are about the initial page load, the client is likely to end up downloading all your dependencies as they explore your application

  • For SC, those dependencies will always be only on the server since those React Server Components are not shipped to the front-end until they have been rendered.

  • Just like what happens with SSR, the server is going to fetch the data from the backend. But we don’t need to wait till we get the data from the backend. There are parts of the app like the header and the side panel that we can render without the data. So, the server renders these components and streams them to the browser.

Conclusion

  • SSR / CSR / SSG 's main concern is about the page

  • Server Component / Client Component main concern is about the component

  • Since a page can be consisted of multiple components, so the page can be the mixture of Server rendering , Static generation and client side rendering if using latest approach

References

The serialized tree from server
The reconstructed tree from client
LogoHow React server components work: an in-depth guideTeam Plasmic
LogoRendering: Composition Patterns
LogoReact δΈ­εŒζž„οΌˆSSRοΌ‰εŽŸη†θ„‰η»œζ’³η† - ζŽ˜ι‡‘
LogoProds and cons of using SSP to build your SPAsdotCMS - Digital Experience Platform
LogoReact | η”¨ε―¦δ½œδΊ†θ§£ Server-Side Rendering ηš„ι‹δ½œεŽŸη†Medium
LogoReact Server Components vs. Server-Side RenderingThe Armchair Critic