Video Summary and Transcription
This Talk explores the suspense component in React and its benefits in handling fetched data. It delves into the rendering process of React components and how suspense anticipates requests. The offscreen fiber is introduced as a hidden component that ensures state continuity. The Talk also discusses the usage of suspense for handling concurrent queries and throwing promises, as well as the integration of Redux and the upcoming changes in React 19. Overall, the Talk provides insights into the workings of suspense and its potential applications in software development.
1. Introduction to Suspense
Today we're going to talk about the suspense component and why we love it. With suspense, we can directly use fetched data without worrying about loaders or errors. Now let's dive deep into React and understand how it works.
Hi, everyone. I'm Charlotte. I'm a React Native Tech Lead at VAM, and I'm super excited to be back here with you today.
Today we're going to talk about a very special component, suspense. You know why suspense? You know why it's such a powerful tool? You know why we love them? But do you know how suspense works? How does suspense know a request is going to happen in my children? I should display a letter instead.
Today we're going to dive deep into the suspense component, and as we do this, we're going to learn more about React as well. So this won't be a talk about concurrency. We're going to solely focus on this component. But before we dive into the how of suspense, let me recap the why. Why do we love suspense so much?
Before suspense, our components used to look like this. We fetched some data, displayed a loader while it was loading, an error if we had to, and finally we reached to the part that's really the most interesting one about our components, the one where we really bring value to the user. With suspense, our components now look like this. We fetch some data, and we can directly use it. We don't have to bother with this loader and error edge cases anymore. They are handled above. Above our components, we define this suspense boundary that handles the loader, and this error boundary that handles the error. This way, in our components, we can directly use our data. This is why we love suspense so much. No more loaders, no more errors spread throughout all of our components. We can directly get to the data.
Now let's get into the how. For the how, we're going to need to dive deep into React. Before this, let me give you a quick reminder of how React works. React has a few fundamental roles. One of them is this one. React calls components and hooks. This means that React decides when it wants to render your components. You don't. When we call our components, we do it this way, with this JSX syntax, but calling a component this way does not mean that it will be executed right away, at least not right away. When we instantiate a component like this, with this JSX syntax, JSX is actually just syntactic sugar, and is equivalent to the call of this JSX function.
2. Building the Fiber Tree
JSX function instantiates fibers in the virtual tree of React elements. React decides when to render and re-render components based on this tree. We trigger a render by clicking a button and React updates the corresponding fiber.
And this JSX function, when it is called, instantiates a node into the virtual tree of fibers of our React elements, and each one of these nodes is called a fiber. That's a term you may have heard before. When we build our app for the first time, React creates this virtual tree with our components and their data, and, from this tree, it decides when to render and re-render our components.
Let's build this fiber tree together. The first component we instantiate with this JSX syntax is app, so we create this app node, this app fiber, but we won't be executing this app function right away. React will add this work in progress pointer to the fiber. Work in progress is a target that targets the fiber that it is currently working on. React works kind of like a game loop. While working progress, while there is fiber to work on, we perform some work over this fiber. Maybe render it. Maybe re-render it. Then we move on to the next one. So React goes through our tree this way until it reaches the end of the tree or until another render happens.
What happens at render? What happens if we click this button right here? We trigger a set state. We are going to render. So React is going to add this render flag to the fiber that holds the state that was just changed. A fiber is really just an object where you can store some values, so you can easily just add this render property if you want to. It's just an object. React is then going to go through our tree again and render the components it wants to.
3. Tree Rendering Process
React goes through the tree from top to bottom, rendering components based on state changes and parent rendering. Render flag is added to the fiber with changed state. App is not rendered.
React goes through our tree from top to bottom, so the next fiber is A. React renders A, so we execute this function. We create here the paragraph and the button fiber because of this JSX syntax, and so on and so forth. When B is rendered, we execute this B function and we create this paragraph as well. And this is our tree.
Now what happens at render? What happens if we click this button right here? We trigger a set state. We are going to render. So React is going to add this render flag to the fiber that holds the state that was just changed. A fiber is really just an object where you can store some values, so you can easily just add this render property if you want to. It's just an object. React is then going to go through our tree again and render the components it wants to. Beginning at the top of our tree.
A component is going to get rendered for either one of two reasons. Either if it holds a state that was just changed, meaning if it was flagged by this render flag, when we call set state, React flags the fiber that holds the state with this render flag, then it matches this criteria. Or a component is going to get rendered if its parent got rendered. So here app does not belong to either of these cases. So app is not going to get rendered.
4. Understanding Suspense
A, paragraph, and button get rendered due to parent rendering, while B and its paragraph do not. Suspense handles displaying children or a loader based on requests happening inside. How does suspense anticipate requests and work? It starts with the first render, where children are rendered and requests trigger the display of a loader. The trick is throwing promises to interact with suspense without access to its code.
Then we can move on to the next fiber. A is going to get rendered because of this render flag. It matches this criteria. And so are the paragraph and the button, because their parent got rendered. As for B and this paragraph, they don't hold any state that was just changed and their parent did not get rendered, so they don't get rendered either. And this is all you need to know for what's coming next.
Suspense. The job of suspense is to either display the children or a loader if a request is happening inside the children. But when suspense is rendered, how does it know a request is going to happen in the children? I should display the fallback instead. Knowing that React renders components from top to bottom, how does it know a query is going to happen below in the tree in advance? How does suspense work? That's the question we're going to try to answer today.
So let's begin from the very start. Let's say it's the first render. Suspense is first going to try to render the children. So it adds this children fiber and React will execute it. So we execute this fetch data function that freely just launch a promise. We launch a request here. So we'd like to let suspense know, hey, we have a loader over here. We have a request. Please display a loader. And how can we, from this promise, from our own code, interact with suspense? Remember this line from React's code. This fiber tree with this suspense component we'd like to interact with is defined at this level. While our component with our promise is run within somewhere within this work function. So from the scope of my code, I don't have access to React's code. I don't have access to suspense, nor do I want to as a user of this API. I don't want to bother with any details of implementation. So how does this work? The trick I found really interesting is this one. We don't just execute a promise. We throw it. We throw this promise. And this work function that's somewhere underneath executes our components is actually nested within this try catch.
5. Working with Suspense
When a promise is thrown to suspense, React climbs the tree to find the closest suspense boundary and adds the didSuspense flag. It adds a listener to the promise and moves the work in progress pointer to the suspense boundary. Suspense renders the fallback when didSuspense is true, and then flips the flag back to false. When the promise resolves, React adds the render flag to the suspense boundary and displays the children again.
So when we throw this promise to your suspense, it bubbles up until it reaches this catch. And here we're inside React's codes. So here, React can decide, can talk to suspense and ask it to display a loader. So, several things are going to happen in this catch. First, React is going to climb up the tree to find the closest suspense boundary. And it is going to add to it this didSuspense flag to true. Again, just a property you add to the fiber. Then it is going to add a listener over the promise so that it knows when it ends and can act on it. And lastly, it is going to move this work in progress pointer up to the suspense boundary and start the rendering process over from there.
We're going to render suspense here. But this time, with didSuspense to true, it knows that the previous render got suspended. So it knows it has to display the fallback. So it will remove this children fiber and instead add this fallback. Before it moves on, it will flip this didSuspense flag back to false because it already handled the suspension. And moving on, we display our fallback. Good. We've got our fallback on the screen. But only half the work is done here because soon the query is going to resolve. When the promise is done, React knows it because of the listener it attached to the promise. So it can act on it. It will add this render flag to the suspense boundary and start over a new three traversal, a new rendering loop beginning with app which is not rendered. Remember these criteria. It does not hold the state that was just changed. Its variant did not get rendered. But suspense is because of this render flag. Suspense is rendered with didSuspense false this time. Remember that suspense flips back the didSuspense flag to false when it handled the suspension when it displayed the fallback. So it knows it has to display the children again. So we are going to run through our children function and the promise is resolved so we can directly see our data on the screen. Great.
6. Understanding the Offscreen Fiber
Now, if another query happens, suspense won't remove the children fiber completely. The offscreen fiber displays or hides the portion of the tree based on the visible property. Offscreen prevents data loss and ensures state continuity. It's a hidden component under development, used to smooth transitions and improve app performance. In summary, suspense displays children, then the fallback if a request occurs. When the query resolves, suspense renders the children again. Finally, what happens if there's a re-render above the fallback?
Now that we are done, if another query is going to happen, this time suspense won't completely remove the children fiber from the screen. Children is actually nested within this offscreen fiber. The goal of offscreen is to either display the portion of the tree that's located below or to hide it based on this visible property. If it is true, you display it. If it's false, you block the work in progress targets. So you don't go below and you can't see the components located below. This is very important because if we removed the children fiber, we would lose all the data that's within it. The goal of fiber is not only to know which components we have in our tree. It's also to know what we have in them. If we add, so, yeah, another promise happening. Oh, sorry, got mixed up in my slides. If another promise happening, suspense switches the visible property to false and displayed the fallback. Okay.
So, if another query is happening, you don't want to lose the data of children. If we add this count data to children, this state is actually going to be held within this fiber. This means that when you render children, you state is going to be reading this value from here. So if we completely removed the children, when we have another promise, when we want to display the fallback again, we would lose our counts and we would start over from the top at the next render. This is the goal of offscreen. From what I've read, offscreen is still under development. It may be used in other cases later like always in the goal of smoothing transitions and making your app faster. But it's not a component you will ever use yourself. It's a hidden component. So, this is in a nutshell how suspense works.
To summarize, first suspense first tries to display the children. Then a request maybe happens in the children in which case suspense displays the fallback. And when the query is resolved, suspense then tries to render the children again. Following this, there were a few things that I wanted to discuss. First, let's say that we're currently displaying a fallback. So here we have in R3 the fallback and the visible property to false. What happens if we have another re-render above in R3? That has nothing to do with the promise being resolved.
7. Working with Suspense: Triggers and Query Handling
To try this out, we can add this state to app and trigger a re-traversal. Suspense displays the fallback and children are rendered again. Multiple queries in one component happen in series, not in parallel. You can launch queries together using useSuspendQuery from react-query. Queries in different components may cause problems.
To try this out, we can add this state to app and trigger this set state here. So when we click this button, we are going to add this render flag to the fiber that holds the state that was just changed and trigger a new re-traversal. App is rendered because of the flag and so is suspense because its parent got rendered. So we render suspense with this did suspense flag to false. We remember that suspense switched back the did suspense flag once it has displayed the fallback. So we have rendered this component with did suspense false. So it decides to display the children again. So we are going to go through this function. We are going to run into the promise again that we throw. We are going to go back to suspense which will display the fallback again. I just find it fascinating that React is so fast that we don't even notice that all of this is happening right under our notice.
Now onto the second conclusion. If you have several requests, several queries inside one component, these two queries are actually going to happen in series. They won't be launched together. They won't be launched in parallel. Suspense is first going to display the children. We're going to hit this promise, throw it. We suspend, display another. And when it's resolved, suspense re-renders this children component again and only then do we reach this line. But that's really bad for performance, isn't it? I was actually really surprised to see that I didn't see that big of an impact. I tried having several small queries and it didn't really, I didn't really see a lot of differences. But this may be a problem. If you have lots of big queries, you may want to launch them together. So you can do this about this. Instead of throwing multiple promises, you can throw them all at once. This is what useSuspendQuery from react-query does as opposed to useSuspendQuery. I won't talk about other state query handlers because react-query is really the only one that I know of. So if you want to launch your queries in parallel, you may want to use this one. There are still some other optimizations made, though. I'm sorry, you may have actually a problem if your queries are in different components.
Handling Concurrent Queries and Q&A
Queries launched in series, not in parallel. Use useSuspendQuery to prefetch data earlier for faster query launch. Suspense launches queries of its direct children. React 19 shows loader asap. Future mix of 18th and 19th behavior. Q&A session: What day is it today? Friday.
If I have a first component that launches a query that then handles this other component that has this other query, these two queries will not be launched in parallel. And useSuspendQuery can't do anything for you here. But I don't think that it's such a bad thing for suspense because before suspense, this still was the case. Before suspense, you had this loader that blocked your rendering process. So it doesn't change much. But you may want to prefetch your data earlier above in your app to launch your queries faster.
There are still, as I said, some optimizations made. Suspense will launch the queries of all of its direct children, meaning that if there is a query in profile, suspense will still try to launch at least the first queries of help and newsletter of all of the siblings. That's the behavior of React 18. In React 19, this won't be the case anymore because the React team realized that it was better to show a loader as fast as possible. But they may one day come back to a mix of the 18th and 19th behavior. You can learn more about this here, but they may one day throw as fast as possible to show a loader, then trigger schedule another rendering pass for the siblings.
And this is all I wanted to share with you today about suspense. I hope you enjoyed digging through its darkest secrets. So I've been developing 18 years, and I have no clue what you are doing. So hats off. Thank you so much. Wow. We're going to jump into the audience questions now. I have to say, this is my first Q&A, and I'm really stressed about this one. OK. We're gonna ease into it. Please. First question, then. Just to ease you, what day is it today? I have no idea. If I can't answer that, I should leave the stage. Friday. It's Friday. OK. Yeah, you're right.
Throwing Promises and Error Boundaries
Throwing promises as a normal part of code execution may feel wrong, but it can be beneficial when nested within an API or used at the framework level. It allows for the removal of loaders and errors. However, caution should be exercised and it is not recommended for normal code usage. Next question from Ensgar: Can a component get suspended by throwing any promise inside it? Yes, this is similar to how error boundaries work.
We can soon. OK. What color is the floor? I'd say it's gray. I hope we agree. OK. Then a real question. Throwing promises as a normal part of code execution feels a bit wrong. Can throw be reserved for exceptions? Oh. OK. So this... Sorry. I had to read it three times. No worries. This is very right, but you're nested within an API. That's not something that you should do. Usually you use a request handler or another library that does this, and yeah, it doesn't seem right, but it's nested, it's hidden. So as it enables you to remove all of your loaders, all of your errors, I think it has so much benefits that it's OK. So don't do it in your normal code, but on the framework level, we'll allow it. Or if you want to do it in your code, I don't know why this would be a good option, but you could do it and just hide it in a function that just... With a warning, we're doing this here, don't do this anywhere else. I know this is dirty, don't judge me. Yeah. All right.
Next question. From Ensgar. Charlotte. So you can just throw any promise inside a component, and the component will get suspended? Yeah. From what I've read. Yeah. Actually, this is pretty much how error boundary works as well.
Throwing Promises and Fallback Behavior
When throwing a promise, React checks if it is for suspense. Suspense children do not necessarily need to be async components, but can execute a promise. What happens if a fallback suspends in the fiber tree? It may result in an error or an endless loop. The compatibility of suspense with promise.all is uncertain. The timing of suspense picking up data fetching inside useEffect with empty dependencies is unclear due to the upcoming removal of useEffect in React 19.
You throw, and it bubbles up into the same tricatch, and React checks the arguments that you're pressing to this error thrown. If you have a promise, it guesses it must be for suspense. Cool. Thank you.
Next question. Do suspense children need to be async components, or do they just need to execute a promise? The suspense children is gone. Do suspense children need to be async components, or do they just need to execute a promise? That's a really good question. I guess that it doesn't... I'm not sure, I haven't tried. But I guess it doesn't have to be asynchronous. I just made it asynchronous to get the results, but I guess if you throw, you throw. So that's a good question, we should try this one. Five into the source.
Question from Rob. Charlotte, what happens if the fiber tree... What happens in the fiber tree if a fallback also suspends? Wow, this is a really good question. I guess you have an error. I think we should definitely try this one out. But I guess you may have an endless loop. Everyone loves endless loops, that's fine.
Does suspense also work with promise.all? I haven't tried it, but I guess so, yes. I really don't know. That's a valid answer. I mean, if it doesn't, it's just like a few lines of code that could be added to React and they decided not to. Okay. All right, next up. When does suspense pick up data fetching inside useEffect with empty dependencies? So when we want to fetch data only once. Well, useEffect is going away with React 19. Yeah. I really don't know.
React 19, Redux Integration, and Loader Display
In React 19, useEffect won't be used anymore due to the new compiler. Integration of Redux with suspense is uncertain. React query states that suspense support is experimental, but it's being used in production. Displaying loaders in suspense may require suspense-enabled frameworks, except for pre-React 19.
Sorry. I'm assuming it's not necessary because in React 19, we're not going to be using useEffect anymore because of the new fancy compiler that we're all happy about.
All right. How does suspense integrate with Redux, if you know that? I have no idea. I haven't tried. I don't know why that would be an issue. Probably. Yeah. Would you say the senior answer? It depends. Maybe we should try and meet Mark Erickson here and ask him. Well, let's try.
All right. React query still states that suspense support is experimental. Are you already using it in production? Yes, we are. Yeah. I didn't... Quite frankly, I didn't know it was still experimental. I think it's safe, but I... Yeah. It's safe enough. I do, but if they say it, maybe we shouldn't. The company is still running. No one went bankrupt. Then it's good to go. Our app was not refused by the store yet.
All right. The docs mention that displaying loaders in suspense only works with suspense-enabled frameworks. Does the pattern you show work without such a framework? I don't think so. I must have followed the documentation, so I guess I must have added it. I think that mention that suspense-enabled frameworks are the only way it works are pre-React 19.
Understanding React 19 Suspense and Promises
In React 19, we need to understand how suspense works and read the source code. A question arises about timeouts and promises in child components. How does suspense identify the component that triggered the promise? We'll ask Lou to connect on Twitter for more information. Another question asks if React MonkeyPatch promises to make them throwable, but the speaker is unsure.
Because in React 19 world, I think it already works. I have really no idea. We need to read the source.
A question from Lou. What's happening if the child component contains something like a timeout and then it throws a promise? I don't see... I don't see why the timeout would affect the promise. Yeah. Probably if it stops the render cycle. Or if it... Oh, if the promise happens within the... Timeout. Okay. I get it. That's really a good question. I have to remember.
How does suspense know that this component triggered the promise? I don't remember this part. That's a good question. How does suspense know that this is the component that threw this promise? I've got to say. I don't remember. Sorry. We'll ask Lou to look you up on Twitter, and then you can find out together. I can check out afterwards. I'm sorry. No, you're not here because you know everything. You know a little bit, and we want to have that bit of knowledge. So don't worry.
Next question is from Ren. Did React, MonkeyPatch promise to make it throwable, or how does that work? I really don't know. But a promise is throwable. Yeah, I don't know React Monkey, I'm sorry.
Caching Promises and Using Suspense for Full Pages
Ren asked about caching promises with OffscreenComponent in React 17. The speaker suggests doing an NPM update for better understanding. Another question asks if it is good practice to use suspense for full pages with a loading fallback. The speaker recommends having only one loader instead of multiple loaders for better UX.
We don't know, Ren. Sorry. Alex Pax is asking, do you mean with OffscreenComponent, we don't need to cache promise for suspense to work? And Alex is still on React 17. I don't know why we need to cache a promise. Oh. With Offscreen. Okay. So the goal of Offscreen is not to keep the promises in cache. It's to either show or hide your children, whether you want to show the fallback or the children. I'm not sure I understand the question.
All right. Well, it's a bit hard to answer since Alex is still on React 17. The advice would be to maybe do an NPM update. Next question. Is it considered a good practice to use suspense to render full pages with a loading fallback? So if you wrap your entire app with a suspense for a loader? For full pages? Well, I don't know about design best practices, but I guess you want to have as much as you want only one loader instead of having multiple loaders and have a cascade of loaders. So this is pretty much what we do. But I'm not sure it's the best practice.
Comments