<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ritik on Medium]]></title>
        <description><![CDATA[Stories by Ritik on Medium]]></description>
        <link>https://medium.com/@ritiksinha91?source=rss-9bf8bdf807ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-tJRUkJqqcsqF4AD</url>
            <title>Stories by Ritik on Medium</title>
            <link>https://medium.com/@ritiksinha91?source=rss-9bf8bdf807ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 19:01:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ritiksinha91/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Comprehensive Guide to Server-Side Rendering (SSR) in React]]></title>
            <link>https://medium.com/@ritiksinha91/a-comprehensive-guide-to-server-side-rendering-ssr-in-react-5a3460fad925?source=rss-9bf8bdf807ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a3460fad925</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Ritik]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 13:46:23 GMT</pubDate>
            <atom:updated>2024-12-06T13:46:23.570Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastering Server-Side Rendering in React: From Basics to Hydration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1RvuCKFrY-z2UWPfsG2Jg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sapegin?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Artem Sapegin</a> on <a href="https://unsplash.com/photos/turned-on-macbook-pro-near-brown-ceramic-mug-ZMraoOybTLQ?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><blockquote>“CSR crafts experiences in the browser, prioritizing speed and interactivity, while SSR lays the foundation on the server, ensuring faster loads and SEO strength. It’s not a battle of better — it’s a decision of purpose.”</blockquote><h3>Client-Side Rendering (CSR): A High-Level Overview</h3><h4>1. The Journey of a CSR React App</h4><ul><li><strong>Initial Request to the Server:</strong> The browser sends a request to the server for the application.</li><li><strong>HTML Response:</strong> The server responds with a minimal HTML file, usually containing a &lt;div&gt; tag (often with an id like root) where the React app will mount.</li><li><strong>JavaScript and Assets Loading: </strong>The HTML includes &lt;script&gt; tags linking to JavaScript and other assets (like CSS). The browser fetches these files and executes the JavaScript.</li><li><strong>Rendering React Components:</strong> The React library initializes, and the components in your app render dynamically within the root element.</li><li><strong>Interactivity:</strong> Once the JavaScript loads and executes, the app becomes fully interactive.</li></ul><h4>2. Components of a React Build</h4><p>When you build your React app for production (using tools like Webpack or Vite), the output typically includes:</p><ul><li><strong>Main JavaScript Bundle</strong>: Contains the logic for your app, split into chunks to optimize load time.</li><li><strong>Vendor Bundle</strong>: Includes external libraries like react and react-dom.</li><li><strong>Static Assets</strong>: Files like CSS, images, and fonts.</li></ul><h4>Example: Basic CSR Response</h4><p>The HTML served during the initial request might look like this:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;My React App&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;/static/css/main.123456.css&quot; /&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;script src=&quot;/static/js/vendor.987654.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;/static/js/main.123456.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h4>3. Advantages of CSR</h4><ul><li><strong>Rich Interactivity</strong>: <br>React’s <strong>Virtual DOM</strong> allows for efficient updates to the UI, ensuring smooth user experiences by only updating the parts of the DOM that have changed. This results in fast, fluid interactions, such as live content updates and seamless UI transitions.</li><li><strong>Client-Side Routing</strong>:<br>CSR apps make use of <strong>client-side routing</strong>, meaning that when users navigate to different parts of the app, only the necessary components are loaded dynamically. This eliminates the need for full-page reloads, providing a <strong>faster navigation experience</strong>. By fetching only the required data and content, the app feels snappier and more responsive.</li><li><strong>Decoupling from Server</strong>:<br><strong>CSR</strong> allows for greater decoupling of the client and server. Once the initial bundle is loaded, the client takes full control of rendering, which reduces the dependency on the server for most subsequent requests. This decoupling not only <strong>improves portability</strong> but also allows for easier integration with third-party APIs, reducing the complexity of backend management.</li></ul><h4>4. Drawbacks of CSR</h4><ul><li><strong>Initial Load Time (FCP Impact)</strong>:<br>CSR often delays the <strong>First Contentful Paint (FCP)</strong> because the browser must download, parse, and execute JavaScript before rendering any meaningful content. This delay can create a poor user experience, especially on slower networks or devices.</li><li><strong>SEO Challenges</strong>:<br>While search engines like Google are increasingly capable of rendering JavaScript, CSR still poses risks for <strong>search engine optimization (SEO)</strong>. Search bots may struggle to index content accurately or might ignore dynamically rendered content altogether, leading to poor visibility in search results.</li><li><strong>Low-Performance Devices</strong>:<br>CSR places a heavy computational load on the user’s browser. On low-performance or older devices, this can lead to laggy experiences, high memory usage, and even crashes when dealing with complex applications.</li><li><strong>Poor Perceived Performance</strong>:<br>Even though the JavaScript bundle loads quickly, the user perceives the application as slow because nothing visible is rendered until hydration completes. This “white screen” effect reduces user satisfaction.</li></ul><h3>Introduction to SSR and Its Role in React</h3><h4>What is Server-Side Rendering (SSR)?</h4><p>Server-side rendering (SSR) is a technique where the HTML content of a webpage is generated on the server rather than in the browser. In the context of React, SSR means rendering your React components on the server and sending fully formed HTML to the client. This approach differs from the default client-side rendering (CSR), where the client (browser) builds the HTML after receiving a JavaScript bundle.</p><h4>How SSR Fits in React?</h4><p>React by default uses Client-Side Rendering (CSR), where the browser loads an initial HTML page with minimal content, then fetches JavaScript files to build and render the full app. While CSR provides rich interactivity and a fast user experience once the app is loaded, it can lead to slower initial page loads.</p><p>SSR comes into play to solve this issue. By pre-rendering the HTML on the server, the user receives a fully rendered page on the first load, which significantly improves the perceived performance. Once the page is loaded, React hydrates the server-rendered content to enable client-side interactivity, similar to CSR.</p><h3>Key Differences Between CSR and SSR</h3><p>Here’s a comparison of CSR and SSR, which will help highlight the advantages and trade-offs of each approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*LsPVvTCbjgPaP6h-jiw_4Q.png" /></figure><h3>When Should You Use SSR?</h3><ul><li><strong>Improved Initial Load Performance</strong>: SSR can significantly improve perceived performance by sending fully rendered HTML to the client on the initial page load.</li><li><strong>Better SEO</strong>: If your React app needs to be indexed by search engines (e.g., blogs, e-commerce sites), SSR can help search engines crawl your site more easily.</li><li><strong>Content-rich Pages</strong>: For pages where the content is mostly static or semi-static, SSR ensures users can see the content immediately while the app loads in the background.</li></ul><h3>Setting Up SSR in React</h3><p>Now that we have a solid understanding of what SSR is and how it differs from CSR, let’s proceed to the implementation.</p><h4>1. Client-Side Rendering (CSR) Setup for Hydration</h4><p>For SSR, we’ll start by rendering the initial HTML on the server, but once it reaches the browser, we need to “hydrate” the React app to make it interactive. This means attaching event listeners and ensuring the app works like a typical client-side React app.</p><p>Here’s how the <strong>Client-Side</strong> code looks:</p><p><strong>ClientApp.tsx</strong></p><pre>import { BrowserRouter } from &#39;react-router-dom&#39;;<br>import { hydrateRoot } from &#39;react-dom/client&#39;;<br>import App from &#39;./App&#39;;<br><br>// Hydrate the root div with the App component<br>hydrateRoot(<br>  document.getElementById(&#39;root&#39;) as HTMLDivElement,<br>  &lt;BrowserRouter&gt;<br>    &lt;App /&gt;<br>  &lt;/BrowserRouter&gt;<br>);</pre><ul><li>The hydrateRoot function is used to attach React’s event listeners and re-enable React&#39;s internal state management to the pre-rendered HTML.</li><li>This happens after the server has delivered the HTML, ensuring that the app becomes interactive without re-rendering from scratch.</li><li>BrowserRouter is used to enable routing on the client side.</li></ul><h4>2. Server-Side Rendering (SSR) Setup</h4><p>On the server side, React will render the HTML content before sending it to the client. This enables faster loading times since the browser gets an already populated HTML page.</p><p><strong>ServerApp.tsx</strong></p><pre>import {<br>  renderToPipeableStream,<br>  RenderToPipeableStreamOptions<br>} from &#39;react-dom/server&#39;;<br>import { StaticRouter } from &#39;react-router-dom/server&#39;;<br>import App from &#39;./App&#39;;<br><br>const render = (url: string, opts: RenderToPipeableStreamOptions) =&gt; {<br>  const stream = renderToPipeableStream(<br>    &lt;StaticRouter location={url}&gt;<br>      &lt;App /&gt;<br>    &lt;/StaticRouter&gt;,<br>    opts<br>  );<br><br>  return stream;<br>};<br><br>export default render;</pre><ul><li>renderToPipeableStream is used to generate the HTML markup for a given route on the server.</li><li>StaticRouter is used instead of BrowserRouter because it doesn’t require any client-side JavaScript to manage the routes.</li><li>The location prop in StaticRouter specifies the route the user is visiting, so React knows which component tree to render.</li><li>render function is invoked with the request URL, and it returns a stream that can be sent to the client.</li></ul><h4>3. Express Server Setup</h4><p>Now that we have the basic server-side and client-side rendering setup, we need to serve the application through an Express server.</p><p><strong>server.js</strong></p><pre>import express from &#39;express&#39;;<br>import fs from &#39;fs&#39;;<br>import path from &#39;path&#39;;<br>import { fileURLToPath } from &#39;url&#39;;<br>import renderApp from &#39;./dist/server/ServerApp.js&#39;;<br><br>const __dirname = path.dirname(fileURLToPath(import.meta.url));<br><br>const PORT = process.env.PORT || 5000;<br><br>const html = fs<br>  .readFileSync(path.resolve(__dirname, &#39;./dist/client/index.html&#39;))<br>  .toString();<br><br>const parts = html.split(&#39;not rendered&#39;); // Placeholder in index.html for where React will be injected<br><br>const app = express();<br>app.use(<br>  &#39;/assets&#39;,<br>  express.static(path.resolve(__dirname, &#39;./dist/client/assets&#39;))<br>);<br><br>app.use((req, res) =&gt; {<br>  res.write(parts[0]); // Serve the static part of the HTML (before React&#39;s server-rendered content)<br><br>  const stream = renderApp(req.url, {<br>    onShellReady() {<br>      stream.pipe(res); // Pipe the server-rendered HTML to the response stream<br>    },<br>    onShellError() {<br>      res.status(500).send(&#39;Error occurred while rendering the shell.&#39;);<br>    },<br>    onAllReady() {<br>      res.write(parts[1]); // Inject the remaining HTML (e.g., closing tags)<br>      res.end(); // End the response<br>    },<br>    onError(err) {<br>      console.log(err); // Log errors during SSR rendering<br>    }<br>  });<br>});<br><br>console.log(`listening on http://localhost:${PORT}`);<br>app.listen(PORT);</pre><p>The server.js file acts as the <strong>backbone of our SSR app</strong>, orchestrating how server-rendered content and client-side interactivity are delivered to the user. Let’s break it down step by step:</p><ol><li><strong>Reading the Static HTML File</strong>:<br>We begin by reading the index.html file generated during the client-side build process. This HTML serves as a template, containing placeholders where React will inject server-rendered and hydrated content.</li><li><strong>Splitting the HTML</strong>:<br>The HTML is split into two parts:</li></ol><ul><li><strong>Before React’s rendering</strong>: This includes the &lt;head&gt; and the initial &lt;div id=&quot;root&quot;&gt;not rendered&lt;/div&gt; placeholder.</li><li><strong>After hydration</strong>: This part represents the closing tags and any content to be appended after React has hydrated the app.</li></ul><p>Splitting allows us to stream the initial HTML quickly, improving perceived performance.</p><p>3. <strong>Serving Static Assets</strong>:<br>The Express server is configured to serve static files like JavaScript and CSS from the client build directory. These assets are essential for enabling client-side interactivity after hydration.</p><p>4. <strong>Handling the Request Lifecycle</strong>:<br>When a user requests a route:</p><ul><li>We serve the <strong>first part of the HTML</strong> immediately to minimize the time to <strong>First Contentful Paint (FCP)</strong>.</li><li>React’s renderToPipeableStream handles rendering the component tree based on the requested route. The rendered content is streamed to the client progressively.</li></ul><p>5. <strong>Streaming Callbacks</strong>:</p><ul><li>onShellReady: This callback is triggered when the server has enough data to render the shell of the application. At this point, we pipe the React stream to the response, allowing the user to see the initial UI as soon as possible.</li><li>onAllReady: This fires when the React rendering is fully complete, including asynchronous content like lazy-loaded components. We append the <strong>second part of the HTML</strong> (post-hydration) and end the response.</li><li>onShellError and onError: These callbacks handle rendering errors gracefully, ensuring the app doesn&#39;t crash on the server or client.</li></ul><p>6. <strong>Enhancing Performance</strong>:<br>The progressive streaming approach, combined with React’s callbacks, ensures that users see content faster, even for large or dynamic applications.</p><p>By combining streaming, splitting, and precise control over the rendering lifecycle, the server.js file efficiently bridges the gap between server-rendered content and client-side interactivity.</p><h4>4. Package.json Configuration</h4><p>To build and run the SSR setup, we need the appropriate scripts in the package.json to build the client and server parts and start the application.</p><p><strong>package.json</strong></p><pre>{<br>  &quot;dev&quot;: &quot;vite&quot;,<br>  &quot;build:client&quot;: &quot;vite build --outDir ../dist/client&quot;,<br>  &quot;build:server&quot;: &quot;vite build --outDir ../dist/server --ssr ServerApp.tsx&quot;,<br>  &quot;build&quot;: &quot;npm run build:client &amp;&amp; npm run build:server&quot;,<br>  &quot;preview&quot;: &quot;vite preview&quot;,<br>  &quot;format&quot;: &quot;prettier --write \&quot;src/**/*.{js,jsx,ts,tsx}\&quot;&quot;,<br>  &quot;lint&quot;: &quot;eslint \&quot;src/**/*.{js,jsx,ts,tsx}\&quot; --quiet&quot;,<br>  &quot;typecheck&quot;: &quot;npx tsc --noEmit&quot;,<br>  &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>  &quot;start&quot;: &quot;node server.js&quot;<br>}</pre><ul><li>The build:client script runs Vite’s build process for the client-side assets.</li><li>The build:server script builds the server-side code using Vite’s SSR mode with ServerApp.tsx.</li><li>The build script runs both client and server builds in sequence.</li><li>The start script starts the server with the built files using node server.js.</li></ul><h4>5. HTML Template</h4><p>The index.html file is where the app’s HTML structure is defined. It contains a div element with an id=&quot;root&quot;, which will later be hydrated by React.</p><p><strong>index.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Adopt Me! v8&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;./style.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div id=&quot;modal&quot;&gt;&lt;/div&gt;<br>    &lt;div id=&quot;root&quot;&gt;not rendered&lt;/div&gt;<br>    &lt;script type=&quot;module&quot; src=&quot;./ClientApp.tsx&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><ul><li>The div with id=&quot;root&quot; serves as a placeholder for where the SSR-rendered content will be injected.</li><li>The not rendered placeholder text will be replaced with the hydrated React content once the JavaScript bundle is loaded.</li><li>The script tag at the bottom loads the ClientApp.tsx script to hydrate the app.</li></ul><h3>Streaming in SSR</h3><h4>An Overview</h4><p>Streaming in SSR refers to the technique of sending HTML to the client as it’s being generated by the server, instead of waiting for the entire page to be rendered before sending any content. This allows for faster loading times and an improved user experience, especially for larger pages.</p><p>React’s renderToPipeableStream allows us to stream the HTML markup from the server to the client, which provides several benefits over traditional SSR. Let’s dive deeper into how this works.</p><h4>How Streaming Works</h4><p>When React renders a page on the server, instead of rendering everything at once and sending the full page to the client, it streams the content piece by piece. Here’s how:</p><p><strong>Server-Side Rendering with Streaming</strong>:</p><ul><li>React generates HTML for the route in chunks and sends each chunk to the client as soon as it’s available.</li><li>As soon as React finishes rendering part of the page (like the header, main content, etc.), it sends that to the client.</li><li>The client starts rendering the content without waiting for the entire page to be available.</li></ul><p><strong>Why Use Streaming?</strong></p><ul><li><strong>Faster First Byte</strong>: Since the browser receives the HTML as it’s being generated, it can start rendering parts of the page as soon as they arrive.</li><li><strong>Improved User Experience</strong>: Users see parts of the page almost immediately instead of waiting for the entire page to load.</li></ul><h4>React’s renderToPipeableStream for Streaming</h4><p>React provides renderToPipeableStream for streaming server-rendered content. Here’s how it works in the context of the code we’ve written for SSR:</p><pre>import { renderToPipeableStream } from &#39;react-dom/server&#39;;<br>import { StaticRouter } from &#39;react-router-dom/server&#39;;<br><br>const render = (url: string, opts: RenderToPipeableStreamOptions) =&gt; {<br>  const stream = renderToPipeableStream(<br>    &lt;StaticRouter location={url}&gt;<br>      &lt;App /&gt;<br>    &lt;/StaticRouter&gt;,<br>    opts<br>  );<br><br>  return stream;<br>};</pre><ul><li>renderToPipeableStream begins rendering the app as a stream.</li><li>Each chunk of HTML is sent to the client progressively, allowing for faster rendering in the browser.</li></ul><h3>What is Hydration?</h3><h4>Defining Hydration</h4><p>Hydration is the process where the static HTML generated on the server is “activated” by React on the client side. The HTML from the server is essentially a static shell, and React’s job is to “take over” the static content and make it interactive.</p><p>Once the HTML is fully loaded and the JavaScript bundle is downloaded, React will:</p><ul><li>Attach event listeners to the pre-rendered HTML.</li><li>Restore React’s internal state for the app, such as component state and routing.</li></ul><p>Hydration occurs after the server has sent the HTML to the client, and React uses it to re-attach the interactivity.</p><h4>Why is Hydration Necessary?</h4><p>Without hydration, the server-rendered HTML would just be a static page, and the user wouldn’t be able to interact with it like a normal React app. Hydration ensures that the page becomes fully interactive once the JavaScript bundle is loaded.</p><h3>Hydration and Client-Side Interactivity</h3><h4>Hydration Process</h4><p>When a user first visits a page, the server sends them a fully rendered HTML document. However, this document isn’t interactive until the JavaScript is executed. This process is called <strong>hydration</strong>.</p><p>React hydrates the app by:</p><ol><li><strong>Attaching event listeners</strong>: React hooks up the interactivity of components (such as click events or form submissions) that were part of the server-rendered HTML.</li><li><strong>Restoring state</strong>: React synchronizes the component state from the server to ensure that the app is interactive in the exact state it was before the page was rendered.</li></ol><h4>The Hydration Lifecycle</h4><ol><li><strong>Initial Request</strong>: The browser requests the page from the server.</li><li><strong>Server-Side Rendering</strong>: The server renders the HTML and sends it to the client.</li><li><strong>Hydration</strong>: Once the HTML arrives at the client, React takes over and rehydrates the page.</li><li><strong>Interactive App</strong>: After hydration, the app is fully interactive.</li></ol><h4>Challenges with Hydration</h4><ol><li><strong>Mismatched Markup</strong>: If the server-rendered HTML differs from what React expects, the hydration can fail, and React will need to re-render the page.</li></ol><ul><li>This can happen if there are dynamic elements in the server-rendered content (like date/time or content based on user-specific data).</li><li>The solution is to ensure consistency between server and client rendering.</li></ul><p>2.<strong> Performance Issues</strong>: Hydration can be a costly operation, especially for large applications with complex DOM trees. Optimizing hydration can improve performance.</p><ul><li>Split the JavaScript bundles.</li><li>Use React’s lazy loading to load parts of the app only when needed.</li></ul><h3>How React Transitions from Server-Rendered HTML to a Fully Interactive App</h3><h4>The Process of Transition</h4><p>Once the server-rendered HTML is loaded in the browser, React needs to “take over” and make the page interactive. This process involves:</p><ol><li><strong>Client-Side JavaScript Bundle</strong>: The client downloads the JavaScript bundle that contains the React app.</li><li><strong>React’s Hydration Mechanism</strong>: React uses the hydrateRoot function to take over the server-rendered HTML, attaching event listeners and managing the state.</li></ol><p><strong>Hydration Example</strong></p><p>Here’s how React hydrates the page:</p><pre>import { hydrateRoot } from &#39;react-dom/client&#39;;<br>import App from &#39;./App&#39;;<br><br>hydrateRoot(<br>  document.getElementById(&#39;root&#39;),<br>  &lt;App /&gt;<br>);</pre><ul><li>React hydrates the existing HTML in the root div.</li><li>The hydrateRoot function ensures that the page doesn&#39;t re-render but instead &quot;activates&quot; the content already in the DOM.</li></ul><h4>Why This Process is Important</h4><p>The transition from server-rendered HTML to an interactive app is crucial for performance and user experience. It prevents unnecessary re-rendering, ensuring that users see content quickly and interact with it immediately after loading.</p><h3>Challenges and Best Practices</h3><h4>Common Challenges in SSR and Hydration</h4><ol><li><strong>Content Mismatch</strong>: As mentioned, mismatches between the server-rendered HTML and client-rendered HTML can lead to React failing to hydrate correctly. This often occurs due to dynamic data that changes between the server and client.</li><li><strong>Performance Bottlenecks</strong>: Streaming and hydration can be slow, especially with large apps. This can lead to a poor user experience with delayed interactivity.</li></ol><h4>Best Practices for Hydration and SSR</h4><ol><li><strong>Minimize Hydration Time</strong>:</li></ol><ul><li>Split your code into smaller bundles using React.lazy and React.Suspense.</li><li>Optimize your bundle size by using tools like webpack or vite to split bundles.</li></ul><p>2. <strong>Ensure Consistency</strong>:</p><ul><li>Ensure that the content rendered on the server matches exactly with what React expects on the client. This helps avoid unnecessary re-renders or errors during hydration.</li></ul><p>3. <strong>Defer Non-Essential JavaScript</strong>:</p><ul><li>Defer loading JavaScript that isn’t critical for the initial page load. Use async or defer attributes to load scripts without blocking HTML rendering.</li></ul><p>4. <strong>Progressive Hydration</strong>:</p><ul><li>Implement <strong>progressive hydration</strong>, where critical parts of the page are hydrated first, followed by less critical content. This can speed up the interactive experience.</li></ul><p>“To sum up, SSR is a powerful technique that can greatly enhance the performance and SEO of your React applications. From understanding how it differs from CSR to implementing it step-by-step, I’ve covered all the essential aspects you need to get started.</p><p>I encourage you to experiment with SSR in your projects and explore advanced tools like Next.js to push your understanding further. If you have any questions or thoughts, let me know in the comments — I’d love to hear from you!</p><p><strong>Note</strong>: “While Server-Side Rendering (SSR) focuses on rendering components on the server and sending HTML to the client, React Server Components (RSC) introduce a completely different paradigm. Both concepts are often confused but serve distinct purposes. If you’re curious about the differences, feel free to reach out — I’d be happy to explain!”</p><p>Stay tuned for more in-depth posts on modern web development. Until then, happy coding!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a3460fad925" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>