React: Suspense and Error Boundaries

published on Fri Sep 06 2019

React Suspense

Suspense in React is an API to render conditional UI. It lets you render a particular component while waiting for another component to load. This can be useful in many scenarios, say

To understand the API for React Suspense, we’ll look at a simple Suspense in an example

const OtherComponent = React.lazy(() => import("./OtherComponent"));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />
      </Suspense>
    </div>
  );
}

Here, we are wrapping a lazily loaded component with a Suspense and displaying a fallback till the time it’s not loaded. Naturally, a Suspense only makes sense for lazily loaded components, as statically loaded components would already be available on page load.

That’s it for React Suspense. What do you think of this newer succinct API for conditionally rendering components? Do you prefer the older way of using higher-order components?