# Rendering Methods

## Client Side Rendering (CSR)

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFW3x2aqEO8GF2kr3VU%2F-Ma2G8G8yW0XPTq9ER1B%2F-Ma2HXYBv2Nd5jWTGkvJ%2Fimage.png?alt=media\&token=2915a169-9314-4e38-b06e-6bc04b16f2d9)

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

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFW3x2aqEO8GF2kr3VU%2F-Ma2G8G8yW0XPTq9ER1B%2F-Ma2Jy9LCzm8bpEz5c8i%2Fimage.png?alt=media\&token=836ba181-30cf-47f1-9876-30476557d089)

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFW3x2aqEO8GF2kr3VU%2F-Ma2G8G8yW0XPTq9ER1B%2F-Ma2KEx7K8BI3xnG3mBl%2Fimage.png?alt=media\&token=57b55834-86ab-4cce-a8fb-29df636dcf4a)

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

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFW3x2aqEO8GF2kr3VU%2F-Ma2G8G8yW0XPTq9ER1B%2F-Ma2NnouaGBje_FeD0aL%2Fimage.png?alt=media\&token=9badbaa0-8d63-4569-9406-bd7bd4c6c339)

* 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="https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FvWgyuHXzW7f2MRWysOfa%2Fimage.png?alt=media&#x26;token=cf122cc3-970c-411c-9b7c-5728aef37d6d" alt=""><figcaption><p>The serialized tree from server</p></figcaption></figure>

<figure><img src="https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FpBzkdF5aCvCNm6SKxxR0%2Fimage.png?alt=media&#x26;token=5c2eb20b-ded9-4af2-858a-4309c8d87d4a" 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>" %}
