avatarAdhithi Ravichandran

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5615

Abstract

evel</h1><p id="2e7a">What is cool about this new approach is that you can you can interleave Server and Client Components in your application, and behind the scenes, React will seamlessly merge the work of both environments.</p><p id="93fa" type="7">React can render on the client and the server, and you can choose the rendering environment at the component level!</p><p id="7210">In Next.js 13, since all the components within the /app folder are server components by default. You will use the <code>"use client"</code><i> </i>directive if you want to render Client Components.</p><p id="a1aa">In the example below, Counter is a Client Component, because it preserves local state, and has event handlers for a button click. This component, will have a <code>"use client"</code> directive placed on top of the component file, above the imports, to indicate that it is a Client Component.</p><p id="5549" type="7">Once "use client" is defined in a file, all other modules imported into it, including child components, are considered part of the client bundle.</p><p id="7a92"><i>Note</i>: This additional step could be confusing for developers and is part of the learning curve that comes with Next.js 13.</p><div id="c1a3"><pre><span class="hljs-string">'use client'</span>

<span class="hljs-comment">// Client Component, because it stores state and has the use client directive.</span>

<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">Counter</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">const</span> [count, setCount] = <span class="hljs-title function_">useState</span>(<span class="hljs-number">0</span>)

<span class="hljs-keyword">return</span> ( <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span> <span class="hljs-tag"><<span class="hljs-name">p</span>></span>You clicked {count} times<span class="hljs-tag"></<span class="hljs-name">p</span>></span> <span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> setCount(count + 1)}>Click me<span class="hljs-tag"></<span class="hljs-name">button</span>></span> <span class="hljs-tag"></<span class="hljs-name">div</span>></span></span> ) }</pre></div><h1 id="8f68">When to use Client vs. Server Components?</h1><p id="fd0d">You only need to mark components as <code>"use client"</code><i> </i>when they use client hooks such as <i>useState</i> or <i>useEffect</i>.</p><p id="3abc">It’s best to leave components that do not depend on client hooks without the directive so that they can automatically be rendered as a Server Component when they aren’t imported by another Client Component.</p><p id="25c7">This helps ensure the smallest amount of client-side JavaScript.</p><p id="b081" type="7">The goal is to ship the smallest amount of client-side JavaScript.</p><p id="f5e0"><b>Use Client Components when:</b></p><ul><li>You use React hooks such as <i>useState</i>, <i>useEffect</i>, <i>useReducer, </i>etc<i>..</i></li><li>There is interactivity within the component, with event listeners such as <i>onClick()</i>.</li><li>There are custom hooks that depend on state or effects.</li><li>Using React Class Components.</li></ul><p id="8212"><b>Use Server Components when:</b></p><ul><li>You fetch data from the server API.</li><li>Sensitive information needs to be stored (tokens, API keys, etc.).</li><li>You need to access backend resources directly.</li><li>There are large dependencies.</li></ul><h1 id="5984">The Magic of Server-Side Rendering (SSR)</h1><p id="53d9">Next, let’s dive into Server-Side Rendering. Server-Side Rendering is not related to the Server Components, although they do have the term “Server” in both.</p><p id="7d64">In SSR, the server generates the final HTML and sends it to the client. This approach is perfect for pages with data dependencies. Next.js 13 now calls Server Side Rendering as Dyanic Data Fetching. It is good to be aware of the new term, to avoid any confusion.</p><p id="222d" type="7">Server Side Rendering (SSR) = Dynamic Data Fetching</p><p id="57e0">Consider our conference website again. Suppose we have a comments section for each conference talk. The comments are dynamic, changing frequently based on user interactions. Here, SSR is ideal.</p><p id="d9a4">In Next.js 13, you can use the <code>fetch()</code> request to fetch data from the API. What is cool is, by setting the <code>cache</code> option to <code>no-store</code>, we can indicate that the fetched data should never be cached. This mean’s it will dynamically fetch the data otherwise known as Server-Side Rendering.</p><div id="7691"><pre><span class="hljs-comment">// app/conference/speakers/page.js</span>

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getSpeakers</span>(<span class="hljs-params"></span>) {

<span class="hljs-comment">// Server-Side Rendering or Dynamic Data Fetching</span> <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">https://...</span>, { <span class="hljs-attr">cache</span>: <span class="hljs-string">'no-store'</span> }) <span class="hljs-ke

Options

yword">const</span> speakers = <span class="hljs-keyword">await</span> res.<span class="hljs-title function_">json</span>()

<span class="hljs-keyword">return</span> speakers; }

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">Page</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">const</span> speakers = <span class="hljs-keyword">await</span> <span class="hljs-title function_">getSpeakers</span>(); <span class="hljs-comment">// Fetch speaker data</span>

<span class="hljs-keyword">return</span> ( <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">ul</span>></span> {speakers.map((speaker) => ( <span class="hljs-tag"><<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{speaker.id}</span>></span>{speaker.name}<span class="hljs-tag"></<span class="hljs-name">li</span>></span> ))} <span class="hljs-tag"></<span class="hljs-name">ul</span>></span></span> ); }</pre></div><p id="1147">Also notice that with Next.js 13, you can colocate the data fetching inside the React components, using Server Components. This is a newer approach which is better than passing the data between the components as props.</p><p id="2a87" type="7">Data fetching can be colocated inside the React component using Server Components in Next.js 13.</p><p id="4a92">In this example above, you have utilized both Server Components and Server-Side Rendering! Neat!</p><h1 id="7426">Server Components Vs. SSR: What’s the Difference?</h1><p id="fc10">The main difference between Server Components and SSR lies in the ‘when’ and ‘what’.</p><p id="bba6">SSR happens at the time of each page request. The server fetches data, generates the HTML, and then sends this HTML to the client. This process repeats with every request. SSR is great for pages with data that changes frequently, and it’s a fantastic boon for SEO.</p><blockquote id="a154"><p>SSR is the rendering of an entire page (which is composed of several components) on the server; Server Component is executing an individual component on the server, generate a static HTML response, and send it to the client.</p></blockquote><p id="565b">On the other hand, Server Components run once at build time. They execute on the server, generate a static HTML response, and send this to the client. This process doesn’t repeat with every request. As such, Server Components are best for parts of your application that don’t change frequently, and they help in significantly reducing the amount of JavaScript shipped to the client.</p><h1 id="f169">Final Thoughts</h1><p id="ee34">In <a href="https://www.pluralsight.com/library/courses/nextjs-13-fundamentals/table-of-contents">Next.js 13</a>, the line between client and server is becoming more blurred, but in a good way! The introduction of Server Components opens up a whole new level of optimization possibilities, while the powerful capabilities of Server-Side Rendering continue to provide robust solutions for data-dependent, SEO-friendly applications.</p><p id="e7b8">By taking full advantage of these two features, you can create web applications that are both highly performant and user-friendly. Although everything is still new, and could be confusing at first, it is just what it takes with evolving frameworks. Next.js continues to push the boundaries of what’s possible with React and JavaScript, and I can’t wait to see what they come up with next.</p><h1 id="5c80">Resources</h1><p id="f488">Alright folks, that’s a wrap! Hope you enjoyed this article! Here are some resources that will come handy in your journey to learn React and Next.js:</p><p id="5404">You can check out my latest course on Next.js 13 on Pluralsight below:</p><div id="96a6" class="link-block"> <a href="https://www.pluralsight.com/library/courses/nextjs-13-fundamentals/table-of-contents"> <div> <div> <h2>Next.js 13 Fundamentals</h2> <div><h3>In this course, you will learn about Next.js, a fast and popular framework to build React applications. Next.js…</h3></div> <div><p>www.pluralsight.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*J8VDI8WnrRq3q0mb)"></div> </div> </div> </a> </div><p id="434d">This course covers the fundamentals of Next.js 13, and also teaches you to build a demo app using the new <i>/app</i> directory and teaches the concepts of Server Components and Server-Side Rendering.</p><p id="ba69"><b>Official Docs:</b></p><p id="7b2b"><a href="https://beta.reactjs.org/">New React Docs</a></p><p id="4fc6"><a href="https://nextjs.org/">Next.js Docs</a></p><h1 id="08e0">Where can you reach me?</h1><p id="4086">For information on my consulting services visit: <a href="https://adhithiravichandran.com/">adhithiravichandran.com</a></p><p id="9879">To stay connected follow me on Twitter: <a href="https://twitter.com/AdhithiRavi">@AdhithiRavi</a></p><p id="8e16">Subscribe to my stories on Medium <a href="https://adhithiravi.medium.com/subscribe">https://adhithiravi.medium.com/subscribe</a></p><p id="6593">Become a medium member: <a href="https://medium.com/@adhithiravi/membership">https://medium.com/@adhithiravi/membership</a></p></article></body>

The Yin and Yang of Next.js 13 — Understanding Server Components and Server-Side Rendering

Photo by Alex Padurariu on Unsplash

Hello friends! It’s been a while since I wrote a blog post. With a new baby at home, I have been super busy!

Today, we’re going to tackle two buzzwords that have been floating around the React ecosystem: Server Components and Server-Side Rendering (SSR). There seems to be a sense of confusion among the newbies in the React community in grasping these two concepts.

Let’s demystify them and see how they differ in this blog post!

Whats new in Next.js 13 ?

https://nextjs.org/ Logo

Before we get started let’s see what’s new in Next.js 13.

In Next.js 13, there is a new App Router within the directory /app. This contains support for React’s Server Components, and several other new features and opitmizations. All of this is still new and recently the /app folder has been marked stable with version 13.4.

The good news is you can now use the /app folder in production, and tap into some of the new features like Server Components. But since everything is so new, there is still some confusion in the community on how to use Server Components, and the real performance benefits. This is still evolving and in a few months, I am sure there will be much more clarity than what we have today.

Alright, now let’s get started with what we know so far.

Server Components

Server Component is a new concept that has been introduced in React 18, and been adopted by Next.js 13 within the /app folder.

Server Components allow you to render components on the server, and reduce the amount of JavaScript sent to the client.

All components inside the Next.js /app directory are Server Components by default.

Why this shift to Server Components?

Server Image : https://app.pluralsight.com/library/courses/nextjs-13-fundamentals/table-of-contents by Adhithi Ravichandran

React Server Components provides developers the ability to tap into the server infrastructure. Before the introduction of Server Components, React was capable of only client-side rendering. With the introduction of the new Server Components, large dependencies can remain entirely on the server, resulting in a performance boost.

With Server Components initial page load is faster, and the client-side JavaScript bundle size is reduced.

By having portions of your application run on the server, we lessen the amount of JavaScript that needs to be sent to the client, hence improving load times. You can still leverage Client Components, whenever there is new user interactivity. But other than that, the client-side run-time JavaScript bundle size is minimal.

This is a huge win for the React ecosystem, and has been adopted already by Next.js 13.

Let’s consider an example. Suppose we have a conference website, and we want to display the list of speakers on the speakers page. The list doesn’t change too often and doesn’t need interactivity. Here, a Server Component makes perfect sense in this scenario.

// app/conference/speakers/page.js
// Server Component by default

export default async function Page() {
  const speakers = await getSpeakers(); // Fetch speaker data

  return (
        <ul>
            {speakers.map((speaker) => (
                <li key={speaker.id}>{speaker.name}</li>
            ))}
        </ul>
    );
}

Choose Rendering at Component Level

What is cool about this new approach is that you can you can interleave Server and Client Components in your application, and behind the scenes, React will seamlessly merge the work of both environments.

React can render on the client and the server, and you can choose the rendering environment at the component level!

In Next.js 13, since all the components within the /app folder are server components by default. You will use the "use client" directive if you want to render Client Components.

In the example below, Counter is a Client Component, because it preserves local state, and has event handlers for a button click. This component, will have a "use client" directive placed on top of the component file, above the imports, to indicate that it is a Client Component.

Once "use client" is defined in a file, all other modules imported into it, including child components, are considered part of the client bundle.

Note: This additional step could be confusing for developers and is part of the learning curve that comes with Next.js 13.

'use client'

// Client Component, because it stores state and has the use client directive.
 
import { useState } from 'react'
 
export default function Counter() {
  const [count, setCount] = useState(0)
 
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  )
}

When to use Client vs. Server Components?

You only need to mark components as "use client" when they use client hooks such as useState or useEffect.

It’s best to leave components that do not depend on client hooks without the directive so that they can automatically be rendered as a Server Component when they aren’t imported by another Client Component.

This helps ensure the smallest amount of client-side JavaScript.

The goal is to ship the smallest amount of client-side JavaScript.

Use Client Components when:

  • You use React hooks such as useState, useEffect, useReducer, etc..
  • There is interactivity within the component, with event listeners such as onClick().
  • There are custom hooks that depend on state or effects.
  • Using React Class Components.

Use Server Components when:

  • You fetch data from the server API.
  • Sensitive information needs to be stored (tokens, API keys, etc.).
  • You need to access backend resources directly.
  • There are large dependencies.

The Magic of Server-Side Rendering (SSR)

Next, let’s dive into Server-Side Rendering. Server-Side Rendering is not related to the Server Components, although they do have the term “Server” in both.

In SSR, the server generates the final HTML and sends it to the client. This approach is perfect for pages with data dependencies. Next.js 13 now calls Server Side Rendering as Dyanic Data Fetching. It is good to be aware of the new term, to avoid any confusion.

Server Side Rendering (SSR) = Dynamic Data Fetching

Consider our conference website again. Suppose we have a comments section for each conference talk. The comments are dynamic, changing frequently based on user interactions. Here, SSR is ideal.

In Next.js 13, you can use the fetch() request to fetch data from the API. What is cool is, by setting the cache option to no-store, we can indicate that the fetched data should never be cached. This mean’s it will dynamically fetch the data otherwise known as Server-Side Rendering.

// app/conference/speakers/page.js

async function getSpeakers() {

  // Server-Side Rendering or Dynamic Data Fetching
  const res = await fetch(`https://...`, { cache: 'no-store' })
  const speakers = await res.json()
 
  return speakers;
}


export default async function Page() {
  const speakers = await getSpeakers(); // Fetch speaker data

  return (
        <ul>
            {speakers.map((speaker) => (
                <li key={speaker.id}>{speaker.name}</li>
            ))}
        </ul>
    );
}

Also notice that with Next.js 13, you can colocate the data fetching inside the React components, using Server Components. This is a newer approach which is better than passing the data between the components as props.

Data fetching can be colocated inside the React component using Server Components in Next.js 13.

In this example above, you have utilized both Server Components and Server-Side Rendering! Neat!

Server Components Vs. SSR: What’s the Difference?

The main difference between Server Components and SSR lies in the ‘when’ and ‘what’.

SSR happens at the time of each page request. The server fetches data, generates the HTML, and then sends this HTML to the client. This process repeats with every request. SSR is great for pages with data that changes frequently, and it’s a fantastic boon for SEO.

SSR is the rendering of an entire page (which is composed of several components) on the server; Server Component is executing an individual component on the server, generate a static HTML response, and send it to the client.

On the other hand, Server Components run once at build time. They execute on the server, generate a static HTML response, and send this to the client. This process doesn’t repeat with every request. As such, Server Components are best for parts of your application that don’t change frequently, and they help in significantly reducing the amount of JavaScript shipped to the client.

Final Thoughts

In Next.js 13, the line between client and server is becoming more blurred, but in a good way! The introduction of Server Components opens up a whole new level of optimization possibilities, while the powerful capabilities of Server-Side Rendering continue to provide robust solutions for data-dependent, SEO-friendly applications.

By taking full advantage of these two features, you can create web applications that are both highly performant and user-friendly. Although everything is still new, and could be confusing at first, it is just what it takes with evolving frameworks. Next.js continues to push the boundaries of what’s possible with React and JavaScript, and I can’t wait to see what they come up with next.

Resources

Alright folks, that’s a wrap! Hope you enjoyed this article! Here are some resources that will come handy in your journey to learn React and Next.js:

You can check out my latest course on Next.js 13 on Pluralsight below:

This course covers the fundamentals of Next.js 13, and also teaches you to build a demo app using the new /app directory and teaches the concepts of Server Components and Server-Side Rendering.

Official Docs:

New React Docs

Next.js Docs

Where can you reach me?

For information on my consulting services visit: adhithiravichandran.com

To stay connected follow me on Twitter: @AdhithiRavi

Subscribe to my stories on Medium https://adhithiravi.medium.com/subscribe

Become a medium member: https://medium.com/@adhithiravi/membership

JavaScript
React
Web Development
Programming
Nextjs
Recommended from ReadMedium