DEV Community

Cover image for Server-Side Rendering (SSR) and Static Site Generation (SSG) in React: A Deep Dive
Rushi Patel
Rushi Patel

Posted on

Server-Side Rendering (SSR) and Static Site Generation (SSG) in React: A Deep Dive

SSR and SSG in React: A Deep Dive

In today's fast-evolving web landscape, performance and SEO are paramount. As React developers, we often face challenges in delivering fast, efficient, and SEO-friendly applications. Two powerful techniques to address these challenges are Server-Side Rendering (SSR) and Static Site Generation (SSG). In this blog post, we'll explore these rendering strategies in depth---discussing what they are, how they differ from routine client-side rendering, their benefits, how to implement them in React, and more.

Myth: SSR and SSG Are Exclusive to React

Reality: SSR and SSG are generic rendering techniques, not limited to React. They are used in various frameworks like Angular Universal, Nuxt.js (Vue), PHP, Django etc to optimize performance and SEO.


Introduction

Modern web applications need to be not only interactive and dynamic but also quick to load and friendly to search engines. Traditional client-side rendering (CSR) --- where the browser downloads a minimal HTML shell (skeleton) and then renders content using JavaScript --- can sometimes lead to poor performance, especially on slower devices or networks.

This is where SSR and SSG come into play. They offer alternative ways to pre-render content, either on each request (SSR) or at build time (SSG), ultimately leading to improved user experience and SEO. Let's check how they differ from each other.


How Do SSR and SSG Differ from Routine Client-Side Rendering (CSR)?

  • Client-Side Rendering (CSR):
    CSR shifts the heavy lifting (load) to the client's browser. The server sends a skeleton HTML file (with some <div></div>), and JavaScript takes over to render the actual content. While this allows for rich interactivity, it may delay the initial content display, adversely affecting both performance and SEO.

  • Server-Side Rendering (SSR):
    With SSR, the server pre-renders the complete HTML for a page on each request. This means users get fully formed pages right away, which improves the initial load time and SEO. However, this dynamic rendering can increase server load, as every request requires processing.

  • Static Site Generation (SSG):
    SSG builds the HTML pages at compile time. These static files can then be served instantly via a Content Delivery Network (CDN). The approach is incredibly fast and secure, but it's best suited for content that doesn't change frequently.


Why Use SSR and SSG? Benefits & Use Cases

Both SSR and SSG address limitations of CSR by improving:

  • Performance:
    Pre-rendered pages lead to faster Time-to-First-Byte (TTFB) and better perceived performance.

  • SEO:
    Search engines can crawl pre-rendered HTML more effectively, leading to better indexing and ranking. Now a days AI tools also crawl the web pages to provide accurate & latest response.

  • User Experience:
    With faster load times, users are less likely to abandon a page, improving engagement and conversion rates.

  • Flexibility:
    SSR is ideal for dynamic, frequently changing data (e.g., dashboards, e-commerce pages), while SSG is perfect for static content (e.g., blogs, marketing sites, landing pages).


What is Hydration

You might have heard of hydration in Rendering Methods. Let's quickly see what is means.

Hydration is the process where React takes over a pre-rendered HTML page, attaches event listeners, and makes it interactive. Instead of building the DOM from scratch (as in client-side rendering), React "adopts" the existing HTML and efficiently updates it.

How Hydration Works

  1. The server renders and sends static HTML to the browser.
  2. The browser displays the static content immediately, improving perceived performance.
  3. React's JavaScript bundle loads and runs in the background.
  4. React matches the virtual DOM with the actual DOM and attaches event handlers, eventually making it interactive.

As Dan Abramov (one of the core member of React team) puts it:

"Hydration is like watering the 'dry' HTML with the 'water' of interactivity and event handlers."


Deep Dive into Server-Side Rendering (SSR)

Definition & Usage

SSR involves rendering React components on the server on every request, producing a complete HTML page before sending it to the client. Once the browser receives the HTML, React "hydrates" the page---attaching event listeners and making it interactive.

How It Works

  1. Request: A client requests a page.
  2. Render on Server: The server renders the React component tree into HTML.
  3. Response: The server sends this pre-rendered HTML to the browser.
  4. Hydration: The browser loads JavaScript and attaches event handlers, converting the static HTML into a fully interactive application.

Example Code (Next.js Implementation)

// pages/index.js (Next.js example)
export async function getServerSideProps(context) {
  // Fetch data that changes on every request
  const data = await fetchDataFromAPI();
  return { props: { data } };
}

export default function Home({ data }) {
  return (
    <div>
      <h1>SSR with Next.js</h1>
      <p>Data fetched from the server: {data.message}</p>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Advantages

  • Improved SEO: Pre-rendered HTML is easier for search engines to index.
  • Faster Initial Load: Users see content quicker, improving perceived performance.
  • Dynamic Content: Ideal for pages that require real-time data.

Limitations

  • Increased Server Load: Every request triggers a new rendering cycle.
  • Complexity: Managing state and caching strategies on the server can be challenging.
  • Scalability: May require additional infrastructure to handle high traffic.
  • Efforts: Require additional efforts in development with SSR Rendering.

Deep Dive into Static Site Generation (SSG)

Definition & Usage

SSG pre-renders pages at build time, creating static HTML files that are deployed to a CDN. These pages load almost instantaneously since they are served directly without additional processing on each request.

How It Works

  1. Build Time: During the build process, React components are rendered into static HTML.
  2. Deployment: The static files are deployed to a CDN.
  3. Request: When a user requests a page, the CDN serves the pre-built HTML immediately.
  4. Hydration: Similar to SSR, React hydrates the static HTML on the client side.

Example Code (Next.js Implementation)

// pages/blog/[slug].js (Next.js example for SSG)
export async function getStaticPaths() {
  const paths = await fetchBlogPaths(); // e.g., [{ params: { slug: 'my-first-post' } }]
  return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
  const post = await fetchBlogPost(params.slug);
  return { props: { post } };
}

export default function BlogPost({ post }) {
  return (
    <div>
      <h1>{post.title}</h1>
      <article>{post.content}</article>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Advantages

  • Speed: Static files are served quickly via a CDN.
  • Security: No server-side processing reduces the attack surface.
  • Scalability: Easily handles large volumes of traffic without additional server resources.

Limitations

  • Inflexibility for Dynamic Data: Not suitable for content that changes frequently.
  • Rebuild Overhead: Every update to content requires a rebuild and redeployment.
  • Limited Interactivity Pre-Hydration: Content is static until JavaScript is loaded.

Implementing SSR and SSG in React

The React ecosystem has embraced both SSR and SSG, with frameworks like Next.js and Gatsby offering seamless integration.

  • Next.js:
    • SSR: Use getServerSideProps to fetch data on every request.
    • SSG: Use getStaticProps (and getStaticPaths for dynamic routes) to generate static pages at build time.
  • Gatsby:
    • Primarily an SSG framework, Gatsby builds static pages using GraphQL queries during the build process.

Both frameworks manage the heavy lifting with help of hydration, routing, and data fetching and making it straightforward to choose the right strategy for your needs.


SSR vs. SSG: A Comparison Table

Aspect Server-Side Rendering (SSR) Static Site Generation (SSG)
Rendering Time On every request At build time
Content Freshness Always up-to-date Requires rebuild for updates
Performance Good, but can be slower under heavy load Extremely fast with CDN distribution
SEO Excellent Excellent
Server Load Higher (dynamic rendering per request) Minimal (static files served)
Use Cases Dynamic pages (e.g., dashboards, e-commerce) Static pages (e.g., blogs, landing pages)
Complexity More complex setup and state management Simpler, but less flexible for dynamic data

Closing Comments

Understanding SSR and SSG is essential for building high-performance, SEO-friendly React applications. While SSR offers the flexibility needed for dynamic content, SSG provides unbeatable speed and scalability for static content. The choice between them ultimately depends on your project requirements.


For any questions or suggestions, please feel free to comment below. 💬

If you find this article useful, share it with your friends and follow for regular update of such good articles. 🔗

Rushi Patel, Signing Off! 😊

Top comments (0)