Article summary
For the past few months, I’ve been working on a website built with NextJS using the app router. A lot of developers who are new to working with the framework have joined the project. A challenge I’ve seen for all of the developers (myself included) is figuring out when to use server components and when to use regular old client components.
The Problem
Many of the explanations I’ve seen online have made some of these points.
Use server components when:
- You need to optimize for SEO.
- A big database transaction is needed before page load.
- You need to increase performance.
Use client components when:
- You’re using JavaScript.
- You need to use React hooks.
- It involves user interaction.
Sure, most of these (we’ll revisit most in a second) are correct. However, some don’t feel very clear, and some are outright confusing for a newer developer. (“How exactly am I supposed to build a react component without JavaScript?”)
There’s a much simpler way to think about this. If you’re building a new component and you’re unsure if it should be a server component or a client component, just ask yourself this question.
Question: Does this component need to react to anything?
Yes? Client component. No? Server component.
That’s it.
Server components don’t like surprises, and they don’t like change. Before they’ll ever render on a screen, they need to have all of their pieces put into place. Once rendered, they’re frozen in time.
Think about how a server component works. It’s a component rendered on the server and then sent to the browser. “Rendered” means turned into nothing but HTML. Instead of thinking of server components as “React components on the server,” think of them as what they really are: a way to build pure HTML on the server and send it to the browser.
Back to our old friend “most.” The oft-repeated rule that a server component can’t have user interaction is wrong. Of course it can have user interaction. Pure HTML supports it (it’s hard to believe, but remember that the internet did exist before JavaScript)! One of the best use cases for server components is forms, which require no JavaScript. Server components can have features like dropdowns, input fields, and buttons. These are all features supported in pure HTML.
So don’t panic next time you find yourself making another component. Just ask yourself if it needs to be reactive or not.