The Rocky Journey of Data Fetching Libraries in React’s New Streaming SSR

Rate this content
Bookmark

If you use the Next.js app directory, you might not even have noticed it, but you are not only using React Server Components, but you are also using the new streaming SSR feature of React.

That means that on first page load, your Client Components will now be server-side rendered, suspense boundary by suspense boundary, and constantly streamed to the client, where they are rehydrated piece-by-piece.


If you combine that with suspense for data fetching in your client components, you will suddenly be facing hydration mismatches - as your client components will start fetching data on the server, but the data will not be transported to the client.


In this talk, I will go over the rocky journey that we had to go through to support suspense for data fetching in Streaming SSR with Apollo Client, looking at all the curious timing problems that come up with these technologies, and how we try to solve them as best as we can - always with the best possible user and developer experience in mind.

FAQ

React Suspense started as a mechanism for lazily importing files and handling asynchronous operations in React. Initially introduced in October 2018 with React Lazy, it evolved significantly with the introduction of React 18 in March 2022, where it was enhanced into what is now known as concurrent mode, adding more features to improve handling of asynchronous data fetching and UI rendering.

Using Suspense for data fetching in React has been technically possible but not generally recommended. This is due to complexities and potential drawbacks in its implementation across different frameworks, which may lead to inconsistent behavior and difficulties in maintenance and optimization of the code.

Apollo Client began experimenting with Suspense for data fetching by introducing a library called React Apollo Hooks in October 2018, which utilized a workaround with React Lazy. Over time, Apollo Client has integrated Suspense more formally, especially after receiving approval from the React team to proceed with its implementation for data fetching.

In the context of Apollo Client and React, SSR involves rendering components on the server side before sending the HTML to the client. This process helps in loading initial data and improving performance by reducing client-side rendering tasks. Apollo Client specifically uses techniques like executing queries during SSR to fetch necessary data before rendering the HTML.

Current limitations with streaming SSR in Apollo Client include handling data synchronization across server and client, preventing data wastage, and avoiding hydration mismatches. Proposed solutions involve using platform-specific APIs to manage data transport and lifecycle more effectively, and enhancing coordination between server-rendered components and client-side interactions.

The Next.js app router introduces complexities in Apollo Client's data fetching strategy by requiring data to be fetched independently on both server and client sides under certain circumstances. This can lead to issues like duplicated requests and data mismatches, which Apollo Client addresses through specific handling strategies and optimizations in its SSR implementation.

Lenz Weber-Tronic
Lenz Weber-Tronic
28 min
20 Oct, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This Talk discusses the journey of data fetching libraries in React's new streaming SSL, focusing on the use of suspense for data fetching. It covers the backstory of suspense and data fetching, the plan and green light for its implementation, challenges with Next.js app router and SSR, data transport and flushing timing, the importance of timing and data transport, delayed rehydration and stream closure, the need for remaining data and required functionalities, challenges faced by vanilla React users, and audience questions about React server components.

1. Introduction

Short description:

Today I'm going to talk about the rocky journey of data fetching libraries in React's new streaming SSL. It's a frustrating topic, but also very interesting. I'm Lancey Bertronick, a senior staff engineer at Apollo GraphQL, working on the TypeScript Apollo client and co-maintaining Redux toolkit. Find me on Twitter as Fry or on GitHub as Frynias.

Today I'm going to talk about—and I have to read this up—the rocky journey of data fetching libraries in React's new streaming SSL, and I'm terribly sorry for the title And I'm terribly sorry for the talk. I wish I wouldn't have to do it, but here we are. And it's a frustrating topic, but it's also very interesting. I was already introduced. I'm Lancey Bertronick. I'm a senior staff engineer at Apollo GraphQL, and I'm working full time on the TypeScript Apollo client. I'm also co-maintainer of Redux toolkit and do a lot of other open source. I have an ADHD. I have more hobbies than you can count. You can find me on Twitter as Fry or on GitHub and the internet generally as Frynias.

2. The Backstory of Suspense and Data Fetching

Short description:

Let's dive into the backstory of how suspense for data fetching in Apollo client started. In October 2018, React Lazy was introduced, allowing lazy importing of files and bundle splitting. A few months later, the hooks APIs were released. In March 2022, React 18 brought concurrent mode and more features, including the renaming of Suspense. However, the use of Suspense for data fetching was still not recommended. In the Apollo client timeline, React Apollo hooks with suspense support was released in October 2018. In September 2019, the hooks were merged into the Apollo client package, marking the first official mention of suspense for data fetching.

So I said, this is a frustrating topic to me. Those always have a backstory. So let's look into a villain backstory here. How did this all start? It started when we wanted to add suspense for data fetching to Apollo client. And coincidentally, in the last talk you already saw that's working. So at this point I could leave a stage and everything's fine. But it didn't always.

So let's go back in history first and talk about suspense first, because this is the thing that actually it wasn't React forever. Why are we talking about this, this year? Shouldn't this have been a thing we stopped thinking or talking about? So let's talk about the history of suspense first. And we go back to October 2018 when the first suspensy thing was introduced in a React and that was React Lazy, which gave you a way of lazily importing files, doing bundle splitting, loading them later and having React kind of fetch the load, like do the loading state for that like behind the scenes without you having to do it. Um, on the same timeline, a few months later, the hooks APIs came out, like in February, 2019. And in March, 2022, this was a big gap. A React 18 came out and essentially the whole thing was like we have concurrent mode now like Suspense was renamed to concurrent mode and got a lot more features at one point and we were really happy and we're like, yeah, we can start doing this now. But then we scrolled down through the release notes and somewhere in that blog article was a footnote. Uh, in React 18, you can start using Suspense for data fetching and opinionated frameworks like Relay, Next.js, Hydrogen and Remix. And that was the depressing part about this ad hoc data fetching with Suspense is technically possible, but still not recommended as a general strategy. And yeah, we, we, we all like every data fetching lever was kind of experimenting with that, but we are a good community and we are listening to our React overlords. So we, we didn't really release anything, uh, uh, especially not on purpose. I think some, some libraries have something for awhile and then saw that sentence afterwards and proofed it out again. Um, so that's like the official react timeline there's of course, there's a second timeline and that's the Apollo client timeline and I want to remember I want you to keep a focus on this October 18 we are in, in the pre hooks times, hooks are not out yet, but there was a conference talk on hooks just. Right now. Um, and we go back to October 18 and someone actually released the library called React Apollo hooks and that library had suspense support using that React lazy workaround. And I, I, honestly, I was flabbergasted when I looked that up because I wasn't aware of that preparing this. And I just want to say, like, I don't know who did that, but kudos to that person. You are amazing. Um, that was a really, really cute, cool experiment. Um, and in September, 2019, so like half a year after the react hooks came out, and a little while after the Apollo hooks had been in beta for a while, uh, there was an issue where we merged the, uh, the hooks into the real Apollo client package. And that was the first official mention of suspense that I could find in our issues. That was issue 5,357. And it says when react suspense and data fetching approach finalizes.

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 Conference 2023React Advanced Conference 2023
27 min
Simplifying Server Components
Top Content
Server Components are arguably the biggest change to React since its initial release but many of us in the community have struggled to get a handle on them. In this talk we'll try to break down the different moving parts so that you have a good understanding of what's going on under the hood, and explore the line between React and the frameworks that are built upon it.
A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
A Framework for Managing Technical Debt
TechLead Conference 2023TechLead Conference 2023
35 min
A Framework for Managing Technical Debt
Top Content
Let’s face it: technical debt is inevitable and rewriting your code every 6 months is not an option. Refactoring is a complex topic that doesn't have a one-size-fits-all solution. Frontend applications are particularly sensitive because of frequent requirements and user flows changes. New abstractions, updated patterns and cleaning up those old functions - it all sounds great on paper, but it often fails in practice: todos accumulate, tickets end up rotting in the backlog and legacy code crops up in every corner of your codebase. So a process of continuous refactoring is the only weapon you have against tech debt.In the past three years, I’ve been exploring different strategies and processes for refactoring code. In this talk I will describe the key components of a framework for tackling refactoring and I will share some of the learnings accumulated along the way. Hopefully, this will help you in your quest of improving the code quality of your codebases.

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Developing Dynamic Blogs with SvelteKit & Storyblok: A Hands-on Workshop
JSNation 2023JSNation 2023
174 min
Developing Dynamic Blogs with SvelteKit & Storyblok: A Hands-on Workshop
Top Content
Featured WorkshopFree
Alba Silvente Fuentes
Roberto Butti
2 authors
This SvelteKit workshop explores the integration of 3rd party services, such as Storyblok, in a SvelteKit project. Participants will learn how to create a SvelteKit project, leverage Svelte components, and connect to external APIs. The workshop covers important concepts including SSR, CSR, static site generation, and deploying the application using adapters. By the end of the workshop, attendees will have a solid understanding of building SvelteKit applications with API integrations and be prepared for deployment.
Building WebApps That Light Up the Internet with QwikCity
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Miško Hevery
Miško Hevery
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
Building a Shopify App with React & Node
React Summit Remote Edition 2021React Summit Remote Edition 2021
87 min
Building a Shopify App with React & Node
Top Content
WorkshopFree
Jennifer Gray
Hanna Chen
2 authors
Shopify merchants have a diverse set of needs, and developers have a unique opportunity to meet those needs building apps. Building an app can be tough work but Shopify has created a set of tools and resources to help you build out a seamless app experience as quickly as possible. Get hands on experience building an embedded Shopify app using the Shopify App CLI, Polaris and Shopify App Bridge.We’ll show you how to create an app that accesses information from a development store and can run in your local environment.
React Performance Debugging
React Advanced Conference 2023React Advanced Conference 2023
148 min
React Performance Debugging
Workshop
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)