GraphQL in the World of React Server Components

Rate this content
Bookmark

In this talk, we'll examine how GraphQL fits into the React Server Component paradigm and how to use Apollo Client, a client-side data store, in a world of streaming SSR. Starting with a demo built with only Server Components with GraphQL, and juxtaposing it with an app using only Client Components, we'll show why a framework with a client-side data store that can also interact with RSC is the best of both worlds alongside good practices when combining it with GraphQL.

This talk has been presented at React Advanced 2024, check out the latest edition of this React Conference.

FAQ

React Advanced 2024 focuses on using GraphQL with React Server Components and Apollo Client to build advanced user experiences.

Suspense in React Server Components allows for asynchronous data fetching, enabling components to suspend until data is available, thus optimizing loading states and improving user experience.

GraphQL fragments are reusable units of fields that allow splitting complex data into smaller parts, useful for defining data requirements for specific UI components.

The 'defer' directive allows certain fields in a GraphQL query to be streamed later, enabling incremental data loading and improving user experience by rendering available data sooner.

Data can be fetched by creating an Apollo Client instance scoped to a single request using the 'register Apollo Client' function and utilizing the 'getClient' helper function to perform queries in server components.

GraphQL serves as a unifying layer between microservices, allowing React Server Component applications to fetch data through a unified API instead of directly querying databases.

Upcoming features include suspense-enabled fragments for streaming data in multi-part chunks and support for other meta frameworks built on React Server Components.

In client components, Apollo Client uses the 'useSuspenseQuery' hook to fetch data, which is initiated during server-side rendering and streamed to the browser for rendering.

Data that seldom changes should be fetched in server components, while interactive or frequently updated data should be fetched in client components to avoid cache synchronization issues.

A separate package was released because working with React Server Components (RSC) requires different paradigms and practices, such as creating client instances per request to avoid cache sharing and potential data leaks.

Jerel Miller
Jerel Miller
Alessia Bellisario
Alessia Bellisario
25 min
28 Oct, 2024

Comments

Sign in or register to post your comment.
Video Summary and Transcription
Welcome to React Advanced 2024. Gerald Miller and Alessia Bellisario discuss the pairing of GraphQL and server components and its advantages. GraphQL combined with server components has been widely adopted, allowing for initial rendering on the server and optimizing performance. React Server Components introduce a new primitive for rendering on the server and executing server-only code. GraphQL serves as a unifying layer between microservices. Data fetching in client components involves setting up an Apollo Client instance and provider. Best practices include separating data, avoiding overlap between server and client components, and using the preload query component. Optimize network requests in React using suspense boundaries and avoiding multiple requests. Fragments in GraphQL help optimize data fetching for UI components. Use fragments and the defer directive to stream data incrementally. Add suspense boundaries, useSuspenseFragment hook, and deferred directives to optimize data fetching in React components. Combine React server components and GraphQL for streaming multi-part responses and enhancing user experiences.

1. Introduction to GraphQL and Server Components

Short description:

Welcome to React Advanced 2024. Gerald Miller and Alessia Bellisario discuss the pairing of GraphQL and server components and its advantages.

Welcome, everyone, to React Advanced 2024. My name is Gerald Miller, and I am a principal software engineer at Apollo working as a full-time maintainer on Apollo Client. And hi, everyone, my name is Alessia Bellisario, and I'm a staff software engineer at Apollo also working on Apollo Client.

And I thought we would start by going back in time to last year's React Advanced London in 2023, when Gerald and I delivered a talk called How to Use Suspense and GraphQL with Apollo to Build Great User Experiences. Now, at the time, React server components were on everyone's mind, but discussing them was an explicit non-goal of our talk that showcased how to use suspense effectively with Apollo Client. And I'll just note, you can feel free to come back and use the QR code on this slide to look it up if you want to watch it later.

So, while we didn't focus on RSE last year, this year we'd like to bring you GraphQL in a world of server components. Let's talk about how and why you might pair these technologies and what this stack enables. To start, we'll pose the question that we had on our minds when we first got a glimpse of the new server components paradigm. We honestly wondered the same thing when we set out to provide some compatibility with server components and Apollo Client. And after a year, we can confidently say, yes, GraphQL does have a place in a world of server components. Thank you so much for coming to our talk. That'll be all for today.

2. The Adoption of GraphQL and Server Components

Short description:

GraphQL combined with server components has been widely adopted in the last year. Different paradigms and best practices need to be considered when working with server components. Server components allow for initial rendering on the server, optimizing performance. Apollo Client provides APIs for server-side cache bootstrapping and initial rendering.

No, but seriously, we've been really pleasantly surprised by how much GraphQL combined with server components has been adopted in the last year. And that's reflected in this trend line and this NPM download chart that we see here. This trend line has been continuing on this upward trajectory since really since day one, as we've seen more and more teams using this technology and using it in production with great results. So there's clearly something here. And this is early evidence that engineers love building with these technologies.

Yeah, but you may notice if you take a look at that screenshot there that we've released this under a different package name, you might be asking, like, why is there a need for a separate package? Why not just build this all into Apollo Client Core? And really, the answer is because working with RSC, there's just some different things that we need to keep in mind and just some paradigms that we need to keep track of. So, for example, in server components, it's a best practice that you create your client instances once per request. And the reason for that is because you don't want multiple requests between multiple users to share a cache where you might have data mixing and matching together. That can result in leaked data between your users and could result in maybe some security implications. So we provide some of the utilities to make sure that that happens correctly. And on the client component end, the data that we fetch in the client components is streamed from the server to the browser and used to hydrate the cache on the browser end. And this really helps avoid the requests on the browser themselves since we're already doing the work on the server. If you're really curious about diving into more details, because we're not going to cover too much of the explicit what's going on, I'd highly encourage you to take a look at Lenza's talk from React Advanced last year that digs a little bit deeper into more of the specifics of this library.

Ok, so let's set the table here and talk about what are server components and answer that question. Now, there's so many excellent primers on React server components out there, including Josh Como's blog post, Making Sense of React server components, from which we borrowed the idea for these diagrams. And I've linked that blog post using the QR code in the corner. And you should definitely check it out. Check out Josh's post if you'd like to read more. But here we see the lifecycle of a typical request made to an app, a React app that's using client-side rendering. So when a request comes in from the client, the server or even a CDN will reply with an HTML document that contains a script tag that tells the browser where to fetch the JavaScript bundle necessary to render your app. And this bundle contains your application code and also all the library code that your app needs to render anything to the screen. So once we see that we've downloaded the JavaScript and the browser has parsed that JavaScript, your application code can begin executing. And it's then that any data fetching that's done during render can actually begin. So this might be a fetch call to an API that executes a database query, for example. It's only when that request comes back with data that your app can render content to the screen. So you can imagine the spinners that a user might see here. Now, with server-side rendering, your React application can perform its initial render on the server, which is a nice optimization. Maybe this is just the application shell, or maybe if you're using a meta framework like Next.js, the initial server render can also include some data fetched on the server that gets injected via props for that initial server render pass. But in general, most data will be fetched on subsequent navigations in the browser after hydration that we see in the client, at which point we have the same need to traverse that client server boundary when we make a client fetch for some data that we need from the server. And it's worth noting here that Apollo Client also provides APIs for bootstrapping your cache on the server and performing that initial server render.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Simplifying Server Components
React Advanced 2023React Advanced 2023
27 min
Simplifying Server Components
Top Content
Watch video: Simplifying Server Components
React server components simplify server-side rendering and provide a mental model of components as pure functions. Using React as a library for server components allows for building a basic RSC server and connecting it to an SSR server. RSC responses are serialized virtual DOM that offload code from the client and handle interactivity. The client manifest maps serialized placeholders to real components on the client, enabling dynamic rendering. Server components combine the best of classic web development and progressive enhancement, offering the advantage of moving logic from the client to the server.
Exploring React Server Component Fundamentals
React Day Berlin 2023React Day Berlin 2023
21 min
Exploring React Server Component Fundamentals
Top Content
Watch video: Exploring React Server Component Fundamentals
This Talk introduces React Server Components (RSC) and explores their serialization process. It compares RSC to traditional server-side rendering (SSR) and explains how RSC handles promises and integrates client components. The Talk also discusses the RSC manifest and deserialization process. The speaker then introduces the Waku framework, which supports bundling, server, routing, and SSR. The future plans for Waku include integration with client state management libraries.
From GraphQL Zero to GraphQL Hero with RedwoodJS
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
Tom Pressenwurter introduces Redwood.js, a full stack app framework for building GraphQL APIs easily and maintainably. He demonstrates a Redwood.js application with a React-based front end and a Node.js API. Redwood.js offers a simplified folder structure and schema for organizing the application. It provides easy data manipulation and CRUD operations through GraphQL functions. Redwood.js allows for easy implementation of new queries and directives, including authentication and limiting access to data. It is a stable and production-ready framework that integrates well with other front-end technologies.
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
This Talk discusses handling local state in software development, particularly when dealing with asynchronous behavior and API requests. It explores the challenges of managing global state and the need for actions when handling server data. The Talk also highlights the issue of fetching data not in Vuex and the challenges of keeping data up-to-date in Vuex. It mentions alternative tools like Apollo Client and React Query for handling local state. The Talk concludes with a discussion on GitLab going public and the celebration that followed.
And Now You Understand React Server Components
React Summit 2024React Summit 2024
27 min
And Now You Understand React Server Components
Top Content
In this Talk, Kent C. Dodds introduces React Server Components (RSCs) and demonstrates how to build them from scratch. He explains the process of integrating RSCs with the UI, switching to RSC and streaming for improved performance, and the benefits of using RSCs with async components. Dodds also discusses enhancements with streaming and server context, client support and loaders, server component rendering and module resolution, handling UI updates and rendering, handling back buttons and caching, and concludes with further resources for diving deeper into the topic.
A Practical Guide for Migrating to Server Components
React Advanced 2023React Advanced 2023
28 min
A Practical Guide for Migrating to Server Components
Top Content
Watch video: A Practical Guide for Migrating to Server Components
React query version five is live and we'll be discussing the migration process to server components using Next.js and React Query. The process involves planning, preparing, and setting up server components, migrating pages, adding layouts, and moving components to the server. We'll also explore the benefits of server components such as reducing JavaScript shipping, enabling powerful caching, and leveraging the features of the app router. Additionally, we'll cover topics like handling authentication, rendering in server components, and the impact on server load and costs.

Workshops on related topic

Build with SvelteKit and GraphQL
GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
Scott Spence
Scott Spence
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A
Build Modern Applications Using GraphQL and Javascript
Node Congress 2024Node Congress 2024
152 min
Build Modern Applications Using GraphQL and Javascript
Featured Workshop
Emanuel Scirlet
Miguel Henriques
2 authors
Come and learn how you can supercharge your modern and secure applications using GraphQL and Javascript. In this workshop we will build a GraphQL API and we will demonstrate the benefits of the query language for APIs and what use cases that are fit for it. Basic Javascript knowledge required.
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced 2022React Advanced 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
Sabin Adams
Sabin Adams
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL for React Developers
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
Roy Derks
Roy Derks
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
Mastering React Server Components and Server Actions in React 19
React Summit US 2024React Summit US 2024
150 min
Mastering React Server Components and Server Actions in React 19
Featured Workshop
Maurice de Beijer
Maurice de Beijer
Calling all React developers! Join us for an immersive 4-hour workshop diving deep into React Server Components and Server Actions. Discover how these game-changing technologies are revolutionizing web development and learn how to harness their full potential to build lightning-fast, efficient applications.

Explore the world of React Server Components, seamlessly blending server-side rendering with client-side interactivity for unmatched performance and user experience. Dive into React Server Actions to see how they combine client-side interactivity with server-side logic, making it easier to develop interactive applications without traditional API constraints.

Get hands-on experience with practical exercises, real-world examples, and expert guidance on implementing these technologies into your projects. Learn essential topics such as the differences between Server and Client Components, optimizing data fetching, passing data effectively, and maximizing performance with new React hooks like useActionState, useFormStatus and useOptimistic.

Whether you're new to React or a seasoned pro, this workshop will equip you with the knowledge and tools to elevate your web development skills. Stay ahead of the curve and master the cutting-edge technology of React 19. Don't miss out - sign up now and unleash the full power of React!
Build a Headless WordPress App with Next.js and WPGraphQL
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
Kellen Mace
Kellen Mace
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.