I chose this image for no other reason than because it showed up in the search results for “suspense.” There may or may not be some deeper symbolism discussed later in this article regarding how the polyfill is only halfway faithful much like how this doll has been torn in half, but let’s get back to the subject at hand. Unsplash The best way to understand a software concept is to try and build it yourself. — TB If you love React, you’ve probably heard something about the , but even after watching a or , it was pretty difficult for me to lay my finger on how Suspense works. upcoming Suspense APIs demo two exactly So I put my computer science cap on and decided to try and recreate it with the current version of React v16. A few disclaimers before we get started that my fictional legal team wants to get out of the way. The actual version of Suspense that will ship with React is and efficient than the version in this polyfill. This tutorial & accompanying module are meant mainly for learning and experimental purposes. Also, the current polyfill will likely not play well with SSR. significantly more complicated Hic Draconis! If you only care about the codes, check out , otherwise here we go! react-suspense-polyfill Setting the Stage IMHO, Suspense is a very powerful addition to the core React API surface, and I believe it will have a profound effect on how pragmatic React code is written a few years from now. If you take nothing else away from this article, understand this: At its core, React Suspense works by allowing an async component to throw a Promise from its method. render This polyfill mimics React’s internal support for this behavior by implementing an in the component. If the error boundary encounters a thrown Promise, it waits until that Promise resolves and then attempts to re-render its children. It also handles falling back to loading content if the Promise takes too long to resolve. (explained in detail below) error boundary Timeout I hope this module and accompanying demos make it easier to get up-to-speed with React Suspense. 😄 React.Placeholder is the main public-facing component exposed by React Suspense. Its interface is relatively straightforward, exposing the following props: Placeholder - Amount of time in milliseconds to wait before displaying fallback / loading content. The main reason for adding a delay before displaying fallback content is to prevent loading indicators flashing too quickly before the main async content loads which can be an annoying UI distraction. delayMs - A React Node that will be displayed while any child component is loading have elapsed. This will typically be some type of loading spinner. fallback only after delayMs - A React Node that will be displayed while any child component is loading have elapsed. Note: this optional prop is specific to react-suspense-polyfill and is strictly for the purpose of demoing how suspense works. suspense only before delayMs - A React Node that represents the main content of this Placeholder component which may or may not throw a Promise while loading asynchronous resources. See for some examples of super sexy, async-friendly child components. children react-async-elements is the component you’re most likely to use in your code, but in the spirit of understanding how it works, the majority of the complexity is handled by . Placeholder Timeout React.Timeout The component is a bit more tricky, so let’s break down what’s going on in steps: Timeout The method (Line 50) will initially invoke its render function with a boolean value signifying whether or not this component has hit its timeout since mounting and encountering an async workload. render children ms If the render successfully, all is well with the world and React continues on as normal. 😃 children If any component within the subtree from its method, it will be caught by Timeout’s error boundary, (Line 24). children throws a Promise render componentDidCatch The error handler first starts a timeout for this async work (Line 28), such that the Timeout will fall back to displaying loading content if & when the timeout expires. ms During the time before this Promise may expire, the is (Lines 29 and 63), which essentially means that we’re waiting for some resource to load but it hasn’t taken long enough to justify displaying the fallback / loading content just yet. ms Timeout “in suspense” Once the Promise resolves (Line 43), Timeout once again invokes its render prop (Line 39) with the expectation that this time, the initial asynchronous resource will resolve and all will once again be well with the world. 😃 children synchronously Note that it’s entirely possible for a subtree to contain multiple, independent async resources, in which case the component may repeat steps 3–6 once for each async resource that needs to be resolved. Alternatively, & may be nested like any React component, so it’s entirely possible that a higher-level won’t need to handle an async request that is thrown lower in the React component tree if that request is captured by a Timeout closer to its origin. This follows the public behavior of React error boundaries pretty closely. Timeout Placeholders Timeouts Timeout Hopefully, the and underlying components are now more concrete in terms of how they’re expected to behave. Placeholder Timeout 99% of the time you’ll be working with a simple component and ignoring these details in , but I believe it’s extremely beneficial and empowering to have this type of deeper mental model to rely on for the type of fundamentally game-changing pattern that React Suspense supports. Placeholder Timeout And with that in mind, let’s talk a bit about how this basic mental model differs from the official version that the extremely talented React core team is cooking up! Subtrees upon subtrees upon trees. (Image Credit: ) Unsplash Comparison to Official React Suspense There are two major limitations of this compared with the forthcoming official implementation of React Suspense. polyfill Correctness Okay, so we may have cheated a little bit 😉 There is one important detail that we left out of our implementation in terms of polyfilling the correct behavior. Can you guess what it is? If you’re not sure, that’s completely fine. I had done this whole coding exercise before I realized that had pointed out a potential flaw with this approach, so don’t worry if you’re drawing a blank… Dan Abramov The one potential correctness issue with this approach (that I’m aware of) is that React unmounts the subtree once an error is thrown, which has the unintended side effect of resetting all subtree components and their state each time an async resource is thrown or resolves. Timeout React’s internal implementation of Suspense doesn’t suffer from this issue, as they have full control over tracking component state and can therefore ensure that partially rendered subtrees are properly restored after resolving suspenseful resources. The good news here, however, is that this is very much an edge case, and empirically, I would expect that this doesn’t come into play very often. As long as you follow the 95% use case where the immediate child of is the only potentially async child component, and instead of say, in response to user interaction, you won’t run into any problems. 👍 Placeholder that async child component eagerly loads all async state up front I’m actually curious if it would make sense for React core to enforce this restriction… Efficiency This is the one area where a userland implementation of React Suspense simply can’t come close to the official core implementation. Otherwise, I’m sure the React team would’ve considered implementing this pattern on top of React as opposed to expanding the core React API surface. In particular, the React team has done a lot of work in the past year or so to enable smarter re-use of partial rendering and the ability to suspend low priority updates in favor of higher priority updates that are closer to affecting a user’s perception of application responsiveness. This work is collectively known as React Fiber, and React Suspense should be viewed as one of the first major optimizations that’s been enabled in React core as a direct result of the amazing foundation established with React Fiber. Huge props to , , , , and the rest of the React team + contributors for their work in this area! Sebastian Markbåge Andrew Clark Dan Abramov Sophie Alpert Compatibility This polyfill does not currently support React because error boundaries weren't properly supported until React . If you have ideas on how to add support for React , please submit an and let's discuss! v15 v16 v15 issue Note that React will log an error to the console when using this polyfill regarding the thrown error, but . Unfortunately, there is no way to this error reporting for these types of intentional use cases. :sigh: this console message can safely be ignored disable Wrapping Up If you’ve read this far, please check out the and ⭐️ the repo as a way of saying thanks! full source code I really hope you’ve found this article helpful. If you’re a React junkie, here are some related links: - Similar experiment by . Creating React Suspense in v16.2 Pete Gleeson - Alternative which bundles a pre-built version of Suspense-enabled React allowing you to experiment with React Suspense right meow. By . react-suspense-starter Jared Palmer - Suspense-friendly async React elements for common situations. By . react-async-elements Jared Palmer - More Suspense stuff (code, demos, and discussions). By . fresh-async-react Swyx Have any thoughts that I left out? Let me know below in the comments! ❤️ Before you go… If you liked this article, click the 👏 below, and share it with others so they can enjoy it as well.