Skip to content
youhoc
  • Pages
    • Home
    • Modern App Guidelines
    • Linux
      • Day 1: Linux Distributions & Navigation
      • Day 2: User Management
      • Day 3: File Permission & Ownership
      • Day 4: Package Management
      • Day 5: Services Management
    • Javascript
      • JS The Weird Part
        • Execution Context
        • Types & Operators
        • Objects & Functions
        • Error Handling & Strict Mode
        • Typescript, ES6, Tra
      • Modern JS
        • JS in the Browser
        • Data Storage JSON
        • Modern JS
        • Advanced Objects & Methods
        • Webpack & Babel
        • Async
      • jQuery
        • In-depth Analysis of jQuery
      • React-ready JS
        • Arrow Function
        • Template Literals
        • Logical AND, OR, Ternary, Nullish Operators
        • Destructuring & Rest Operator
        • Array Method
        • Immutability and Spread Operator
        • Promises, Async/Await, Callback
    • PHP
      • gruntJS
      • composer
      • MySQL
    • Docker
      • Container Basics
      • Container Networking
      • Container Image
      • Container Volume & Persistent Data
      • Dockerfile
      • Docker Compose
      • Docker Registry
    • Node.js
      • 1. Installing & Exploring
      • 2. Core Modules
      • 3. Get User Input
      • File System & Input Arguments
      • 5. Express Web Server
      • 6. Deploy to Heroku & Github
      • Authentication
      • 7. Databases
      • 8. Rest API
    • ReactJS
      • React from Andrew
        • Summary from Next
        • 1. Basics
        • 2. React Components
        • 3. Webpack
        • 4. Styling with SCSS
        • 5. React Router
        • 6. React Hook
      • Modern React From The Beginning
        • Intro to JSX
        • Vite Build Tools
        • Basic Component Creation
        • Component State
        • Props & Component Composition
        • useState with Inputs & Form Submission
        • useEffect, useRef & Local Storage
        • Async / Await and Http Request in React
        • React Router: Declarative Mode
        • ContextAPI
        • React Router: Framework Mode
          • File-routing & HTML Layouts
          • icon picker
            Server-side Data Query
          • Links & Navigation
          • Loaders
    • Typescript
      • Type User vs UserProp
    • Payload CMS

Server-side Data Query

Cơ bản về SSR và CSR

With React Router v7, you can choose between server-side rendering (SSR) and client-side rendering (CSR) for your application.
This choice can significantly impact the performance and user experience of your app.
If you open the react-router.config.ts file, you will see the following code:
import type { Config } from '@react-router/dev/config';
export default {
// Config options...
// Server-side render by default, to enable SPA mode set this to `false`
ssr: true,
} satisfies Config;

SSR = server-side rendering

When you use SSR, the server generates the HTML for the page and sends it to the client. This means that the page will load faster because the browser doesn't have to wait for JavaScript to load before rendering the page. This is especially useful for SEO because search engines can crawl the HTML content of the page.
mọi thứ đều được load ở server
không có client-loading / hydration
thời gian đợi chính là thời gian server response time
trong Next.js (cũng là 1 SSR React), tất cả hook (useEffect, useState...) sẽ không work
nhưng trong React Router, hook vẫn work, dĩ nhiên hiểu rằng hook chỉ chạy sau khi client hydration

CSR = client-side rendering

When you use CSR, the server sends a blank HTML page to the client and the JavaScript code is responsible for rendering the page. This means that the page will take longer to load because the browser has to wait for JavaScript to load before rendering the page. This is not ideal for SEO because search engines may not be able to crawl the JavaScript content of the page.
load sẵn index.html rồi mới dùng useEffect và client-loading / hydration để load tiếp nội dung
// VÍ DỤ 1
// console log dưới đây, nếu bật SSR sẽ thấy 2 log, nếu bật CSR chỉ thấy 1 log
const now = new Date().toISOString();
if (typeof window === 'undefined') {
console.log('🖥️ Server Render at:', now);
} else {
console.log('🧠 Client Hydration at:', now);
}
// nếu bật SSR, sẽ thấy cả 2
// nếu bật CSR, sẽ chỉ thấy '🧠 Client Hydration at:...'

// VÍ DỤ 2
// window object chỉ tồn tại ở CSR
const HomePage = () => {
console.log(window.scrollX);
return (
<section>
<h1>Welcome</h1>
</section>
);
};
// nếu bật SSR, sẽ báo lỗi do không tồn tại window object
// nếu tắt SSR (bật CSR), sẽ chạy bình thường

// VÍ DỤ 3
// userEffect vẫn chạy được với React Router nhưng sẽ không chạy được với Next.js
// để an toàn khi chạy CSR bên trong SSR thì phải để trong useEffect
const HomePage = () => {
useEffect(() => {
console.log(window.scrollX);
}, []);

return (
<section>
<h1>Welcome</h1>
</section>
);
};
This may be confusing if you are coming from Next.js because in Next, you can not use `useEffect` on the server.
But in React Router v7, you can use `useEffect`, but it will not run until the client hydrates the page.
So if you want to use something like `window.localStorage`, you can do it inside a `useEffect` hook and it will work on the client.

With the `useState` hook, you can use that in SSR as well but the server will only use the initial state. The client will then hydrate the state and use the updated state.
Delete the `useEffect` and any console logs.
Hopefully, this gives you a good idea of how SSR and CSR work in React Router v7. You can choose the one that fits your needs best. We can also prerender pages to generate static HTML files. We will look at this later.

Data Fetching

Data fetching → client-slide
Data query → server-side

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.