Next.js is a hybrid framework, meaning it allows you to create applications with both server-side rendering and client-side rendering strategies. This architecture allows you to create dynamic web apps, combining the benefits of server-rendered frameworks like Express.js with the interactivity of client-rendered libraries like React.js.
In this lesson, we are going to discuss what are server and client components, and what part of your app should be rendered on the client or server.
Server-side rendering
By default, Next.js renders all the components on the server, and there are reasons for this. Server components come with several advantages over client components:
- Security: Server components offer enhanced security by accessing resources such as databases and APIs directly from the server. This eliminates the need to expose sensitive information to the client, ensuring data remains secure and protected from potential vulnerabilities.
- Performance: Another key benefit is improved performance. By handling data fetching on the server, server components reduce the time required to retrieve and process information, which leads to faster response times and reduced initial load times for your application.
- Caching: Server-side rendering introduces an efficient caching mechanism. Rendered pages can be cached and reused for subsequent requests or shared among other users, further optimizing performance and load times.
- Better SEO: Server-rendered pages also improves SEO. Since the content is rendered and available when the page loads, search engines can easily crawl and index it, enhancing the visibility and discoverability of your application.
Client-side rendering
Server-side rendering does come with issues, and the main disadvantage is the lack of interactivity. Client components give us access to:
- Event Handlers: Such as
onClick()
,onChange()
, which are crucial for building interactive webpages. - React.js APIs: Such as states (
useState()
), side effects (useEffect()
), and other React features. - Browser APIs: Such Clipboard API, Geolocation API, and so on.
You can opt into client components by adding a "use client"
directive at the top of your component, which tells Next.js that we need to work with a client component. For example, here is how we can create a counter app in Next.js.
1"use client";
2
3import { useState } from "react";
4
5export default function Counter() {
6 const [count, setCount] = useState(0);
7
8 return (
9 <div>
10 <p>Count: {count}</p>
11 <button onClick={() => setCount(count + 1)}>Increment</button>
12 </div>
13 );
14}