REACT SERVER COMPONENTS

Introduction

Server and Client Components allow developers to build applications that span the server and client, combining the rich interactivity of client-side apps with the improved performance of traditional server rendering.

Thinking in Server Components

React Server Components introduce a new mental model for building hybrid applications that leverage the server and the client.

Instead of React rendering your whole application client-side (such as in the case of Single-Page Applications), React now gives you the flexibility to choose where to render your components based on their purpose.

Why Server Components?

Server Components allow developers to better leverage server infrastructure. For example, you can move data fetching to the server, closer to your database, and keep large dependencies that previously would impact the client JavaScript bundle size on the server, leading to improved performance.

The initial page load is faster, and the client-side JavaScript bundle size is reduced.

Additional JavaScript is only added as client-side interactivity is used in your application through Client Components.

Client components

Client Components enable you to add client-side interactivity to your application.

The use client directive is a convention to declare a boundary between a Server and Client Component module graph.

When to use Server and Client Components?

Fig.1 - Comparatives.

Patterns

Moving Client Components to the Leaves

Composing Client and Server Components

  • On the server, React renders all Server Components before sending the result to the client.
    • This includes Server Components nested inside Client Components.
    • Client Components encountered during this stage are skipped.
  • On the client, React renders Client Components and slots in the rendered result of Server Components, merging the work done on the server and client.
    • If any Server Components are nested inside a Client Component, their rendered content will be placed correctly within the Client Component.

Nesting Server Components inside Client Components

Nesting Server Components inside Client Components

Unsupported Pattern

				
					
				
			

Nesting Server Components inside Client Components

Recommended Pattern:

Passing Server Components to Client Components as Props

				
			
				
					
				
			

Other topics not covered

  • Using third-party packages.
  • Using context to share state between Client Components.
  • Sharing data between Server Components.

Resources