# Understanding React.Suspense

> React Suspense is a powerful feature that allows developers to pause rendering until a task, such as loading data from an API, is completed.

- Canonical URL: https://marcelocarmona.com/understanding-react-suspense
- Language: English (en-US)
- Published: 2018-12-04
- Tags: React, JavaScript
- Other languages: [Espanol](https://marcelocarmona.com/es/entendiendo-react-suspense)

---

This is a new feature that allows us to "stop" a render until we have finished a task (e.g. loading data from an API).

_[Interactive component: CodeSandbox — see the HTML page]_

We are going to fetch a task when the `Task` component is mounted and save the result in a very simple cache.
The interesting part to understand is that when we throw a promise, it is caught by Suspense and shows a loading state until it is resolved.

```javascript
import React, { Suspense } from 'react'
import ReactDOM from 'react-dom'
import './styles.css'

function fetchFirstTask() {
  return fetch('https://jsonplaceholder.typicode.com/todos/1').then((response) => response.json())
}

let cache = null

function Task() {
  if (!cache) {
    throw fetchFirstTask().then((task) => (cache = task))
  }
  return (
    <div>
      {cache.completed ? '✅' : '⛔️'} {cache.title}
    </div>
  )
}

function App() {
  return (
    <div className="App">
      <h1>My task</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <Task />
      </Suspense>
    </div>
  )
}
```

Sometimes we have a fast connection and the resource is loaded very quickly. In this case, it may not be necessary to show a loading state, so we can use `maxDuration` to avoid this weird blink.

```javascript
<Suspense maxDuration={400} fallback={<div>Loading...</div>}>
  <Task />
</Suspense>
```

---

Site entrypoint for agents: [llms.txt](https://marcelocarmona.com/llms.txt) · [llms-full.txt](https://marcelocarmona.com/llms-full.txt) · [ai-index.json](https://marcelocarmona.com/ai-index.json) · [sitemap.xml](https://marcelocarmona.com/sitemap.xml)

Every HTML page on this site also serves this Markdown representation via
`Accept: text/markdown`, or by appending `.md` to the URL.
