Delving Developer

What is React.Suspense? How do I use it?

Eddie Cunningham
Eddie Cunningham
1 min readReact.js
Cover Image for What is React.Suspense? How do I use it?

React.Suspense is a new feature in 16.6 that allows developers to define what should happen while a component is loading. This makes it easy to create loading states for components without having to duplicate code or use higher-order components.

React.Suspense can only be used with React.lazy to dynamically load components. React.lazy takes a function that returns a promise for the component to be loaded. When the component is resolved, React will render it. If the component takes too long to resolve, React will render a fallback component defined via the fallback property in React.Suspense.

There are future plans to make React.Suspense handle more scenarios such as network requests. This blog post touches on the topic, but there is more work to be done before that point is reached.

How do we use it?link

Below is an example of how we may use React.Suspense. As you can see, we're defining our component dynamically for code-splitting purposes.

import { lazy, Suspense } from 'react'

const Component = lazy(() => import('./Component'))

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <Component />
      </Suspense>
    </div>
  )
}