Next.js Server Components Vs Client Components: a Decision Framework
A look at server components vs client components, an explanation of when to use each, and explaining a common anti-pattern.
Listen to Article
Next.js Server Components Vs Client Components: a Decision Framework
-
In Next.js, the general rule of thumb is to use client components as sparingly as possible.
-
This is because larger client bundles require more JS hydration, hurting your Interaction to Next Paint (INP) and Time to Interactive (TTI).
-
Meaning that the perceived performance of your website will suffer if client components are used excessively.
-
Sometimes client components will need to be used, as your site will likely have to make use of features that are only available in the clients’ browser. Such as:
- In this case, when creating client components, it is important not to fall for a common anti-pattern that will negatively impact your sites performance:
- The "use client" directive opts all child components into client-side rendering.
- It is therefore very easy to accidentally opt several components into client-side rendering, even if they don’t necessarily need to be rendered on the client.
- This will affect your site's Interaction to Next Paint (INP) and Time to Interactive (TTI), negatively impacting the performance for the end user.
Example
Anti-pattern
The anti-pattern appears when you opt content into client-side rendering that is better placed on the server. In the case above, Header and ArticleContent should be rendered on the server as they do not make use of any client side features. Therefore, placing them on the client will increase bundle size unnecessarily.
- In order to preserve your sites performance, you should localise the “use client” directive, so that only code that is essential to run on the client does so.
- The most common case is that a component will contain a mix of functionality that should run on the server and that can only run on the client.
- In this case, for maximum performance you should create new components and mark them with the “use client” directive with only the essential functionality that needs to run on the client.
Solution
Correct design pattern
The correct implementation moves the <button> to a new component (SidebarToggle.tsx) which is marked with the "use client" directive. This is because the button needs to access mouse events which are only available on the client to process the click.
At the same time, Header and ArticleContent are left out of client-side rendering so that the bundle size stays as small as possible and the site's performance is preserved.
Stay Connected
Get notified whenever we publish new articles, insights, guides and product updates.