Async components and Suspense
Lazy-loading components with defineAsyncComponent and its loading, error and retry options, then coordinating async setup with experimental <Suspense>.
Async components and Suspense
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `defineAsyncComponent(() => import('./Heavy.vue'))` returns a wrapper component that only downloads the real one the first time it renders; the bundler turns the dynamic `import()` into a separate chunk, so rarely used components stay out of the initial bundle.
- On its own, an async component can manage its own waiting and failure through the options form: `loadingComponent` (shown after a `delay`, 200ms by default), `errorComponent`, `timeout`, and an `onError(error, retry, fail, attempts)` hook for retries.
- `<Suspense>` waits on two kinds of async dependency anywhere below it: components with an async `setup()` (including `<script setup>` with top-level `await`) and async components, showing its `#fallback` slot until all of them resolve.
- Under a `<Suspense>`, an async component is suspensible by default, so its own loading, error, delay and timeout options are ignored; `suspensible: false` hands control back to the component.
- `<Suspense>` is still marked experimental in the Vue docs as of Vue 3.5, it has no error slot of its own (errors are caught with `onErrorCaptured` in a parent), and it only reverts to the fallback when its default slot's root node is replaced.
Two kinds of “not ready yet”
Some components aren’t ready the moment their parent renders, for two different reasons.
The first is code. An admin dashboard might include a charting library, a rich-text editor and a PDF exporter. If every component is imported statically, all of it ships in the bundle every visitor downloads, including the many who never open the admin panel. The fix is to load that code only when it’s needed.
The second is data. A profile card can’t show anything useful until the profile request resolves. Each such component ends up with its own isLoading flag and spinner, and a page made of five of them shows five spinners popping in at different times.
Vue has a tool for each: defineAsyncComponent for code, and <Suspense> for coordinating waits of either kind.
Lazy loading with defineAsyncComponent
The browser’s dynamic import() returns a promise for a module, and bundlers like Vite treat every dynamic import as a split point that becomes its own chunk (see dynamic import and module bundlers). defineAsyncComponent turns that promise into something you can use in a template:
<script setup>
import { ref, defineAsyncComponent } from 'vue'
const ReportChart = defineAsyncComponent(() =>
import('./ReportChart.vue')
)
const showReport = ref(false)
</script>
<template>
<button @click="showReport = true">Show report</button>
<ReportChart v-if="showReport" :year="2026" />
</template>
ReportChart here is a wrapper. Vue calls the loader function the first time the wrapper is actually rendered — not when the parent loads — and caches the result, so the chunk is fetched once. Props and slots pass straight through, so the parent’s template doesn’t change at all.
A network request can be slow or fail, so there’s an options form:
import { defineAsyncComponent } from 'vue'
import Spinner from './Spinner.vue'
import LoadFailed from './LoadFailed.vue'
const ReportChart = defineAsyncComponent({
loader: () => import('./ReportChart.vue'),
loadingComponent: Spinner,
delay: 200, // wait this long before showing Spinner (default 200ms)
errorComponent: LoadFailed,
timeout: 10_000, // show LoadFailed if it takes longer (default: never)
onError(error, retry, fail, attempts) {
// e.g. a flaky connection: retry fetch failures up to 3 times
if (attempts <= 3) retry()
else fail()
}
})
The delay exists to avoid flicker: on a fast connection, a spinner that appears for 30ms and vanishes looks worse than nothing.
If you know React, this is the counterpart to React.lazy (code splitting and lazy loading), with one difference: a lazy React component relies on a <Suspense> boundary above it for its loading UI, while a Vue async component can handle its own loading and error states without one.
Route-level lazy loading — component: () => import('./views/Admin.vue') in a router config — looks similar but is a Vue Router feature, not an async component; it’s covered with Vue Router and in performance optimization.
<Suspense>: one loading state for a whole subtree
Before using <Suspense>, know its status: the Vue docs mark it as an experimental feature, not guaranteed to reach stable and with an API that may change. As of Vue 3.5, the current stable line, that warning still stands. It’s widely used anyway — Nuxt relies on it — but treat its edge-case behavior as something that can shift.
<Suspense> waits on two kinds of async dependency anywhere in its subtree:
- A component whose
setup()is async. In<script setup>, any top-levelawaitdoes this automatically. - An async component created with
defineAsyncComponent.
<!-- UserProfile.vue -->
<script setup>
const props = defineProps({ id: Number })
const res = await fetch(`/api/users/${props.id}`)
const user = await res.json()
</script>
<template>
<h2>{{ user.name }}</h2>
</template>
<!-- Dashboard.vue -->
<template>
<Suspense>
<div class="grid">
<UserProfile :id="7" />
<ActivityFeed /> <!-- also async -->
</div>
<template #fallback>
<DashboardSkeleton />
</template>
</Suspense>
</template>
On first render, <Suspense> renders the default slot in memory. If it hits any async dependency, it enters a pending state and shows #fallback. When every dependency it found has resolved, it switches to resolved and shows the real content in one go. Both slots allow exactly one immediate child node, which is why the example wraps the two components in a <div>.
A component with an async setup needs a <Suspense> above it. Without one, Vue warns and doesn’t render it, because there’s nowhere to show the waiting state.
A few rules catch people out:
- It doesn’t go back to fallback for every new wait. Once resolved,
<Suspense>only becomes pending again if the root node of its default slot is replaced. A new async component appearing deeper in the tree won’t trigger the fallback. - It keeps old content while new content loads. When it does revert, it keeps showing the previous content until the new content resolves. The
timeoutprop sets how many milliseconds to wait before switching to the fallback;0switches immediately. - It takes over async components. An async component under a
<Suspense>is suspensible by default, so its ownloadingComponent,errorComponent,delayandtimeoutare ignored. Passsuspensible: falseto keep them. - It emits events:
pending,resolveandfallback, useful for a top-of-page progress bar.
React’s <Suspense> plays the same role (Suspense for data fetching), but there it’s stable and works with any component that suspends; Vue’s only knows about async setup and async components.
Errors need a parent
<Suspense> has no error slot. If an async setup throws or an async component fails to load, catch it with onErrorCaptured in the component that renders the <Suspense>:
<script setup>
import { ref, onErrorCaptured } from 'vue'
const error = ref(null)
onErrorCaptured((err) => {
error.value = err
return false // handled; stop it propagating further
})
</script>
<template>
<p v-if="error">Couldn't load the dashboard.</p>
<Suspense v-else>
<DashboardContent />
<template #fallback>Loading…</template>
</Suspense>
</template>
How onErrorCaptured propagates, and how it relates to the app-wide handler, is the subject of the next lesson.
Combining with RouterView, KeepAlive and Transition
When these built-ins wrap a routed page, the docs prescribe a nesting order: <Transition> outermost, then <KeepAlive>, then <Suspense>, then the component.
<RouterView v-slot="{ Component }">
<template v-if="Component">
<Transition mode="out-in">
<KeepAlive>
<Suspense>
<component :is="Component" />
<template #fallback>Loading…</template>
</Suspense>
</KeepAlive>
</Transition>
</template>
</RouterView>
Lazily loaded routes don’t trigger <Suspense> themselves, but async components and async setup inside them do.
What the video covers
Alvaro Saburido (creator of TresJS) explains why Suspense exists, how to use it with async components, how fallback content works, and how to handle errors — the chapters line up with the second half of this lesson. It is lighter on defineAsyncComponent’s own options (loadingComponent, delay, timeout, onError) and doesn’t dwell on Suspense’s experimental status, so the prose above carries those. The Vue School link focuses on top-level await in <script setup> as the async dependency, and John Komarnicki’s video shows the bundle-size motivation in a real Vite build.
Where this fits
Suspense shows “still waiting.” The other half is “it failed,” which is error handling in Vue. Data fetching patterns that don’t need Suspense are in data fetching in Vue, and how Suspense behaves on the server is in SSR and hydration.
Check yourself
What does `defineAsyncComponent(() => import('./ReportChart.vue'))` change about when `ReportChart` is downloaded, compared with a normal `import ReportChart from './ReportChart.vue'`?
A static import puts `ReportChart` (and everything it imports) into the bundle that loads with the parent, so it's downloaded up front whether or not it is ever shown. With `defineAsyncComponent` and a dynamic `import()`, the bundler emits it as a separate chunk, and the wrapper only calls the loader the first time the component is actually rendered, so users who never open the report never download it.
You set `loadingComponent` and `errorComponent` on an async component, but neither ever appears; instead a spinner from higher up the page shows. Why?
The async component is nested inside a `<Suspense>`. Async components are suspensible by default, so when a `<Suspense>` is in the parent chain it takes over the loading state and the component's own `loadingComponent`, `errorComponent`, `delay` and `timeout` options are ignored. Setting `suspensible: false` on the async component makes it handle its own states again.
A component uses `const user = await fetchUser()` at the top level of `<script setup>`. It renders nothing and Vue logs a warning. What is missing?
A top-level `await` makes the component's `setup` async, which turns it into an async dependency that must be rendered inside a `<Suspense>` boundary. Without a `<Suspense>` ancestor, Vue has nowhere to show a pending state and does not render the component. Wrap it (or an ancestor) in `<Suspense>` with a `#fallback`, or fetch in a non-blocking way and handle loading state yourself.
How do you show an error message when an async dependency inside `<Suspense>` rejects?
`<Suspense>` has no error slot. Register `onErrorCaptured` in the component that renders the `<Suspense>`, store the error in a ref, return `false` if it has been fully handled, and use `v-if` to render an error message instead of the `<Suspense>` when the ref is set. The error UI must not re-render the failing content, or it will fail again.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.