# Rendering Methods

## Client Side Rendering (CSR)

![](/files/-Ma2HXYBv2Nd5jWTGkvJ)

### 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)

![](/files/-Ma2Jy9LCzm8bpEz5c8i)

![](/files/-Ma2KEx7K8BI3xnG3mBl)

### 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&#x20;
* 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

![](/files/-Ma2NnouaGBje_FeD0aL)

* 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

```tsx
// 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&#x20;
* 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.

{% code title="wrong.tsx" %}

```typescript
'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 />
    </>
  )
}
```

{% endcode %}

{% code title="correct.tsx" %}

```typescript
'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}
    </>
  )
}
```

{% endcode %}

### Flow

<figure><img src="/files/IGjMKtuZytDu5jbJwbeo" alt=""><figcaption><p>The serialized tree from server</p></figcaption></figure>

<figure><img src="/files/SPkCsTtgWLR89S2rzFzL" alt=""><figcaption><p>The reconstructed tree from client</p></figcaption></figure>

* 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

{% embed url="<https://medium.com/starbugs/react-%E7%94%A8%E5%AF%A6%E4%BD%9C%E4%BA%86%E8%A7%A3-server-side-rendering-%E7%9A%84%E9%81%8B%E4%BD%9C%E5%8E%9F%E7%90%86-c6133d9fb30d>" %}

{% embed url="<https://juejin.cn/post/6844903694870265870>" %}

{% embed url="<https://dotcms.com/blog/post/spas-and-server-side-rendering-a-must-or-a-maybe>" %}

{% embed url="<https://www.thearmchaircritic.org/mansplainings/react-server-components-vs-server-side-rendering>" %}

{% embed url="<https://www.plasmic.app/blog/how-react-server-components-work>" %}

{% embed url="<https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://petercheng7788.gitbook.io/developer-note/frontend/react/core/csr-and-ssr-and-ssg.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
