<Suspense>
<Suspense>
memungkinkan Anda menampilkan fallback sampai komponen children selesai dimuat.
<Suspense fallback={<Loading />}>
<SomeComponent />
</Suspense>
- Referensi
- Pengunaan
- Menampilkan fallback saat konten sedang dimuat
- Mengungkap konten secara bersamaan sekaligus
- Mengungkap konten yang tersusun saat dimuat
- Menampilkan konten yang sudah basi saat konten baru sedang dimuat
- Preventing already revealed content from hiding
- Indicating that a transition is happening
- Resetting Suspense boundaries on navigation
- Providing a fallback for server errors and server-only content
- Troubleshooting
Referensi
<Suspense>
Props
children
: UI aktual yang ingin Anda render. Jikachildren
ditangguhkan sewaktu merender, batas Suspense akan beralih merenderfallback
.fallback
: UI alternatif untuk dirender menggantikan UI yang sebenarnya jika belum selesai dimuat. Setiap node React yang valid akan diterima, meskipun dalam praktiknya, fallback adalah tampilan placeholder yang ringan, Suspense akan secara otomatis beralih kefallback
ketikachildren
ditangguhkan, dan kembali kechildren
ketika datanya sudah siap. Jikafallback
ditangguhkan sewaktu melakukan rendering, itu akan mengaktifkan induk terdekat dari batas Suspense.
Catatan Penting
- React tidak menyimpan state apa pun untuk render yang ditangguhkan sebelum dapat dimuat untuk pertama kalinya. Ketika komponen sudah dimuat, React akan mencoba merender ulang komponen yang ditangguhkan dari awal.
- Jika Suspense menampilkan konten untuk komponen, namun kemudian ditangguhkan lagi,
fallback
akan ditampilkan lagi kecuali jika pembaruan yang menyebabkannya, disebabkan olehstartTransition
atauuseDeferredValue
. - Jika React perlu menyembunyikan konten yang sudah terlihat karena ditangguhkan lagi, ini akan membersihkan layout Effects yang ada di dalam konten komponen. Ketika konten siap untuk ditampilkan lagi, React akan menjalankan Efek tata letak lagi. Hal ini memastikan bahwa Efek yang mengukur tata letak DOM tidak mencoba melakukan hal ini saat konten disembunyikan.
- React menyertakan pengoptimalan di under the hood Streaming Server Rendering dan Selective Hydration yang terintegrasi dengan Suspense. Baca tinjauan arsitektural dan tonton sebuah pembicaraan teknis untuk belajar lebih lanjut.
Pengunaan
Menampilkan fallback saat konten sedang dimuat
Anda dapat membungkus bagian mana pun dari aplikasi Anda dengan Batas Suspense:
<Suspense fallback={<Loading />}>
<Albums />
</Suspense>
React akan menampilkan kode loading fallback sampai semua kode dan data yang dibutuhkan oleh the children telah dimuat.
Pada contoh di bawah ini, Komponen Albums
menangguhkan saat mengambil daftar album. Hingga siap untuk dirender, React mengganti batas Suspense terdekat di atas untuk menunjukkan fallback—Anda Loading
Komponen. Kemudian, saat data dimuat, React menyembunyikan fallback Loading
dan merender komponen Albums
dengan data.
import { Suspense } from 'react'; import Albums from './Albums.js'; export default function ArtistPage({ artist }) { return ( <> <h1>{artist.name}</h1> <Suspense fallback={<Loading />}> <Albums artistId={artist.id} /> </Suspense> </> ); } function Loading() { return <h2>🌀 Loading...</h2>; }
Mengungkap konten secara bersamaan sekaligus
Secara default, seluruh pohon di dalam Suspense diperlakukan sebagai satu kesatuan. Sebagai contoh, meskipun hanya satu dari komponen-komponen ini yang tertahan menunggu beberapa data, semua komponen tersebut akan digantikan oleh indikator pemuatan:
<Suspense fallback={<Loading />}>
<Biography />
<Panel>
<Albums />
</Panel>
</Suspense>
Kemudian, setelah semuanya siap untuk ditampilkan, semuanya akan muncul sekaligus.
Pada contoh di bawah ini, baik Biography
dan Album
mengambil beberapa data. Namun, karena dikelompokkan di bawah satu batas Suspense, komponen-komponen ini selalu “muncul” bersamaan.
import { Suspense } from 'react'; import Albums from './Albums.js'; import Biography from './Biography.js'; import Panel from './Panel.js'; export default function ArtistPage({ artist }) { return ( <> <h1>{artist.name}</h1> <Suspense fallback={<Loading />}> <Biography artistId={artist.id} /> <Panel> <Albums artistId={artist.id} /> </Panel> </Suspense> </> ); } function Loading() { return <h2>🌀 Loading...</h2>; }
Komponen yang memuat data tidak harus menjadi anak langsung dari batas Suspense. Sebagai contoh, Anda dapat memindahkan Biografi
dan Album
ke dalam komponen Rincian
yang baru. Hal ini tidak akan mengubah perilakunya. Biografi
dan Albums
memiliki batas Suspense induk terdekat yang sama, sehingga pengungkapannya dikoordinasikan bersama.
<Suspense fallback={<Loading />}>
<Details artistId={artist.id} />
</Suspense>
function Details({ artistId }) {
return (
<>
<Biography artistId={artistId} />
<Panel>
<Albums artistId={artistId} />
</Panel>
</>
);
}
Mengungkap konten yang tersusun saat dimuat
Ketika sebuah komponen ditangguhkan, komponen Suspense induk terdekat akan menampilkan fallback. Hal ini memungkinkan Anda menyatukan beberapa komponen Suspense untuk membuat urutan pemuatan. Fallback setiap batas Suspense akan terisi saat tingkat konten berikutnya tersedia. Sebagai contoh, Anda dapat memberikan daftar album dengan fallback tersendiri:
<Suspense fallback={<BigSpinner />}>
<Biography />
<Suspense fallback={<AlbumsGlimmer />}>
<Panel>
<Albums />
</Panel>
</Suspense>
</Suspense>
Dengan perubahan ini, menampilkan Biography
tidak perlu “menunggu” sampai Album
dimuat.
Urutan nya adalah sebagai berikut:
- Jika
Biography
belum dimuat,BigSpinner
ditampilkan sebagai pengganti seluruh area konten. - Setelah
Biography
selesai dimuat,BigSpinner
digantikan oleh konten. - Jika
Albums
belum dimuat,AlbumsGlimmer
ditampilkan sebagai penggantiAlbums
dan induknyaPanel
. - Akhirnya, setelah
Albums
selesai dimuat, dia akan menggantikanAlbumsGlimmer
.
import { Suspense } from 'react'; import Albums from './Albums.js'; import Biography from './Biography.js'; import Panel from './Panel.js'; export default function ArtistPage({ artist }) { return ( <> <h1>{artist.name}</h1> <Suspense fallback={<BigSpinner />}> <Biography artistId={artist.id} /> <Suspense fallback={<AlbumsGlimmer />}> <Panel> <Albums artistId={artist.id} /> </Panel> </Suspense> </Suspense> </> ); } function BigSpinner() { return <h2>🌀 Loading...</h2>; } function AlbumsGlimmer() { return ( <div className="glimmer-panel"> <div className="glimmer-line" /> <div className="glimmer-line" /> <div className="glimmer-line" /> </div> ); }
Batas suspense memungkinkan Anda mengoordinasikan bagian mana dari UI Anda yang harus selalu “muncul” bersamaan, dan bagian mana yang harus menampilkan lebih banyak konten secara bertahap dalam urutan status pemuatan. Anda dapat menambah, memindahkan, atau menghapus batas-batas Suspense di mana saja di dalam pohon tanpa memengaruhi perilaku aplikasi Anda yang lain.
Jangan memberikan batas Suspense pada setiap komponen. Batas suspense tidak boleh lebih terperinci daripada urutan pemuatan yang Anda inginkan untuk dialami pengguna. Jika Anda bekerja dengan desainer, tanyakan kepada mereka di mana status pemuatan harus ditempatkan - kemungkinan mereka sudah memasukkannya dalam wireframe desain mereka.
Menampilkan konten yang sudah basi saat konten baru sedang dimuat
Dalam contoh ini, komponen SearchResults
ditangguhkan saat mengambil hasil pencarian. Ketik "a"
, tunggu untuk hasil, dan kemudian edit menjadi "ab"
. Hasil untuk "a"
akan tergantikan oleh loading fallback.
import { Suspense, useState } from 'react'; import SearchResults from './SearchResults.js'; export default function App() { const [query, setQuery] = useState(''); return ( <> <label> Search albums: <input value={query} onChange={e => setQuery(e.target.value)} /> </label> <Suspense fallback={<h2>Loading...</h2>}> <SearchResults query={query} /> </Suspense> </> ); }
Pola UI alternatif yang umum adalah untuk menunda memperbarui daftar dan terus menampilkan hasil sebelumnya hingga hasil yang baru siap. The useDeferredValue
Hook memungkinkan Anda meneruskan versi kueri yang ditangguhkan:
export default function App() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<label>
Search albums:
<input value={query} onChange={e => setQuery(e.target.value)} />
</label>
<Suspense fallback={<h2>Loading...</h2>}>
<SearchResults query={deferredQuery} />
</Suspense>
</>
);
}
query
akan segera diperbarui, sehingga input akan menampilkan nilai baru. Namun, deferredQuery
akan menyimpan nilai sebelumnya sampai data dimuat, jadi SearchResults
akan menunjukkan hasil yang sebelumnya untuk sementara waktu.
Untuk membuatnya lebih jelas bagi pengguna, Anda bisa menambahkan indikasi visual apabila daftar hasil basi ditampilkan:
<div style={{
opacity: query !== deferredQuery ? 0.5 : 1
}}>
<SearchResults query={deferredQuery} />
</div>
Masukkan "a"
didalam contoh berikut ini, tunggu hingga hasilnya dimuat, lalu edit input ke "ab"
. Perhatikan, bahwa alih-alih fallback Suspense, Anda sekarang melihat daftar hasil sebelumnya yang diredupkan sampai hasil yang baru dimuat:
import { Suspense, useState, useDeferredValue } from 'react'; import SearchResults from './SearchResults.js'; export default function App() { const [query, setQuery] = useState(''); const deferredQuery = useDeferredValue(query); const isStale = query !== deferredQuery; return ( <> <label> Search albums: <input value={query} onChange={e => setQuery(e.target.value)} /> </label> <Suspense fallback={<h2>Loading...</h2>}> <div style={{ opacity: isStale ? 0.5 : 1 }}> <SearchResults query={deferredQuery} /> </div> </Suspense> </> ); }
Preventing already revealed content from hiding
When a component suspends, the closest parent Suspense boundary switches to showing the fallback. This can lead to a jarring user experience if it was already displaying some content. Try pressing this button:
import { Suspense, useState } from 'react'; import IndexPage from './IndexPage.js'; import ArtistPage from './ArtistPage.js'; import Layout from './Layout.js'; export default function App() { return ( <Suspense fallback={<BigSpinner />}> <Router /> </Suspense> ); } function Router() { const [page, setPage] = useState('/'); function navigate(url) { setPage(url); } let content; if (page === '/') { content = ( <IndexPage navigate={navigate} /> ); } else if (page === '/the-beatles') { content = ( <ArtistPage artist={{ id: 'the-beatles', name: 'The Beatles', }} /> ); } return ( <Layout> {content} </Layout> ); } function BigSpinner() { return <h2>🌀 Loading...</h2>; }
When you pressed the button, the Router
component rendered ArtistPage
instead of IndexPage
. A component inside ArtistPage
suspended, so the closest Suspense boundary started showing the fallback. The closest Suspense boundary was near the root, so the whole site layout got replaced by BigSpinner
.
To prevent this, you can mark the navigation state update as a transition with startTransition
:
function Router() {
const [page, setPage] = useState('/');
function navigate(url) {
startTransition(() => {
setPage(url);
});
}
// ...
This tells React that the state transition is not urgent, and it’s better to keep showing the previous page instead of hiding any already revealed content. Now clicking the button “waits” for the Biography
to load:
import { Suspense, startTransition, useState } from 'react'; import IndexPage from './IndexPage.js'; import ArtistPage from './ArtistPage.js'; import Layout from './Layout.js'; export default function App() { return ( <Suspense fallback={<BigSpinner />}> <Router /> </Suspense> ); } function Router() { const [page, setPage] = useState('/'); function navigate(url) { startTransition(() => { setPage(url); }); } let content; if (page === '/') { content = ( <IndexPage navigate={navigate} /> ); } else if (page === '/the-beatles') { content = ( <ArtistPage artist={{ id: 'the-beatles', name: 'The Beatles', }} /> ); } return ( <Layout> {content} </Layout> ); } function BigSpinner() { return <h2>🌀 Loading...</h2>; }
A transition doesn’t wait for all content to load. It only waits long enough to avoid hiding already revealed content. For example, the website Layout
was already revealed, so it would be bad to hide it behind a loading spinner. However, the nested Suspense
boundary around Albums
is new, so the transition doesn’t wait for it.
Indicating that a transition is happening
In the above example, once you click the button, there is no visual indication that a navigation is in progress. To add an indicator, you can replace startTransition
with useTransition
which gives you a boolean isPending
value. In the example below, it’s used to change the website header styling while a transition is happening:
import { Suspense, useState, useTransition } from 'react'; import IndexPage from './IndexPage.js'; import ArtistPage from './ArtistPage.js'; import Layout from './Layout.js'; export default function App() { return ( <Suspense fallback={<BigSpinner />}> <Router /> </Suspense> ); } function Router() { const [page, setPage] = useState('/'); const [isPending, startTransition] = useTransition(); function navigate(url) { startTransition(() => { setPage(url); }); } let content; if (page === '/') { content = ( <IndexPage navigate={navigate} /> ); } else if (page === '/the-beatles') { content = ( <ArtistPage artist={{ id: 'the-beatles', name: 'The Beatles', }} /> ); } return ( <Layout isPending={isPending}> {content} </Layout> ); } function BigSpinner() { return <h2>🌀 Loading...</h2>; }
Resetting Suspense boundaries on navigation
During a transition, React will avoid hiding already revealed content. However, if you navigate to a route with different parameters, you might want to tell React it is different content. You can express this with a key
:
<ProfilePage key={queryParams.id} />
Imagine you’re navigating within a user’s profile page, and something suspends. If that update is wrapped in a transition, it will not trigger the fallback for already visible content. That’s the expected behavior.
However, now imagine you’re navigating between two different user profiles. In that case, it makes sense to show the fallback. For example, one user’s timeline is different content from another user’s timeline. By specifying a key
, you ensure that React treats different users’ profiles as different components, and resets the Suspense boundaries during navigation. Suspense-integrated routers should do this automatically.
Providing a fallback for server errors and server-only content
If you use one of the streaming server rendering APIs (or a framework that relies on them), React will also use your <Suspense>
boundaries to handle errors on the server. If a component throws an error on the server, React will not abort the server render. Instead, it will find the closest <Suspense>
component above it and include its fallback (such as a spinner) into the generated server HTML. The user will see a spinner at first.
On the client, React will attempt to render the same component again. If it errors on the client too, React will throw the error and display the closest error boundary. However, if it does not error on the client, React will not display the error to the user since the content was eventually displayed successfully.
You can use this to opt out some components from rendering on the server. To do this, throw an error in the server environment and then wrap them in a <Suspense>
boundary to replace their HTML with fallbacks:
<Suspense fallback={<Loading />}>
<Chat />
</Suspense>
function Chat() {
if (typeof window === 'undefined') {
throw Error('Chat should only render on the client.');
}
// ...
}
The server HTML will include the loading indicator. It will be replaced by the Chat
component on the client.
Troubleshooting
How do I prevent the UI from being replaced by a fallback during an update?
Replacing visible UI with a fallback creates a jarring user experience. This can happen when an update causes a component to suspend, and the nearest Suspense boundary is already showing content to the user.
To prevent this from happening, mark the update as non-urgent using startTransition
. During a transition, React will wait until enough data has loaded to prevent an unwanted fallback from appearing:
function handleNextPageClick() {
// If this update suspends, don't hide the already displayed content
startTransition(() => {
setCurrentPage(currentPage + 1);
});
}
This will avoid hiding existing content. However, any newly rendered Suspense
boundaries will still immediately display fallbacks to avoid blocking the UI and let the user see the content as it becomes available.
React will only prevent unwanted fallbacks during non-urgent updates. It will not delay a render if it’s the result of an urgent update. You must opt in with an API like startTransition
or useDeferredValue
.
If your router is integrated with Suspense, it should wrap its updates into startTransition
automatically.