💡You might have seen a lot of chatter on here about React Server Components recently.
If you're like me, and you didn't quite understand what the hell they are, you'll find this thread helpful 🧵
In essence, React Server Components are just that. React Components that can be rendered on the server before being sent to the client.
But isn't that what Server Side Rendering is? And haven't we been doing that with Next.js for a while?
Yes, and no. To explain lets's look at how React apps are usually rendered.
Imagine we are trying to render the Github issue UI and the components look something like this
If we don't do any server side rendering, this is roughly how our page gets rendered.
The client gets a bundle of JS from the server. After that's downloaded React calls render on the App root and recursively renders every component down the tree.
The problem here is that the user just sees a blank page while the JS bundle is downloaded.
To fix this problem we can try rendering the app on demand and send it pre-rendered over the wire.
Server Side Rendering.
But because we are on the server we can only render to basic html, no interactivity.
The downside here is that we still need to send the bundle of JS alongside that html, so that we can add that interactivity later.
The user experience is better because we can show the user something while the rest of the JS loads.
But we have to quickly hydrate that html so that it is interactive soon after being shown.
React Server Components are a bit different in that they are not just rendered on the server, but they are rendered and then serialised into a weird intermediate format, not html.
That is then bundled with the client components and sent over like normal.
This serialisation process essentially hard codes all the values into the component, removing dependencies.
But it also means it can only be presentational. No state. No event handlers.
That's why our Comment Input can't be a Server Component.
Because Server Components have no interactivity or state, they never get hydrated on the client side.
This means we don't need to send their dependencies over the wire. So the bundle size is much smaller.
They have a few other advantages too:
1. The format they are serialised into is streamable. Which means the the client doesn't need to have downloaded the entire component before it can figure out what to render.
This should play nice with concurrent mode.
2. One of the side effects of hydration is that it resets client state but that doesn't happen with Server Components because hydrate is never called.
3. You could in theory use SSR and Server Components together.
Not sure, but it might work something like this:
I've definitely got a bunch of stuff wrong here but I also tried to keep it simple for the sake of understanding.