Common Misconceptions About React Server Components


React Server Components are a new way of writing React components that speed up server-side & full-stack app development. But let's be real, they've also caused a lot of confusion.
Client components are rendered in both the server and browser.
1- Server generates initial HTML, including Server Components and the initial state of Client Components.
2- The initial HTML is sent to the browser with the JS files of Client components.
3- The initial HTML is displayed on the browser.
4- Components marked with 'use client' become interactive.
If components are only rendered in the browser, it can lead to poor user experience. Users might see a blank page at first and have to wait for JavaScript to run before seeing any content.
This is more likely to happen on slow networks and old devices. It also reduces the website's visibility in search engines.
Next.js solves this by pre-rendering client components on the server. This shows content immediately, improving user experience and SEO.
You can't put Server Components directly inside Client Components. Doing so turns the Server Component into a Client Component, losing its server-side benefits.
But you can pass Server Components as props to Client Components. This keeps their server-rendered nature.
A common pattern is to pass them as the children prop, as shown in the code example below.
This allows you to handle data fetching and heavy tasks on the server, making your app faster while still having interactive client components.
You don't need use client in every component that needs to be rendered on the client.
When you import a Server component inside a Client Component, the server component is rendered as a client component.
Also, all the nested components of that server component, become client components, including their utilities and functions.
Therefore, you only need to make the top-level parent component a "Client Component", then all the nested components are treated as a client component.
In this example, we have a client component 'Home'. The footer and Header are server components. Since they are nested from 'Home', they are treated as client components.
You might accidentally expose sensitive backend code to the frontend, creating security vulnerabilities.
For instance, if you imported a server component that has an authenticateUser function into a client component, that function would now be exposed to the frontend.
If this code is exposed to the client, attackers could examine it and discover the hardcoded admin credentials or understand exactly how your authentication logic works, potentially finding security vulnerabilities.
Luckily, you can prevent this from happening by using server-only, which will throw an error at build time if you try to share backend code in the frontend.
use client, only top-level parent.server-only to prevent code exposure.Get notified when we publish new blog posts
Comments