Showing Granular Fallback Content with Suspense
When fetching data or downloading a resource (e.g., a code file), loading delays can occur—delays that can lead to a bad user experience. You should therefore consider showing some temporary fallback content while waiting for the requested resource.
For that reason, to simplify the process of rendering fallback content while waiting for some resource, React offers its Suspense
component. As shown in Chapter 10, Behind the Scenes of React and Optimization Opportunities, you can use the Suspense
component as a wrapper around React elements that fetch some code or data. For example, when using it in the context of code splitting, you can show some temporary fallback content like this:
import { lazy, Suspense, useState } from 'react';
const DateCalculator = lazy(() => import(
'./components/DateCalculator.jsx'
)
);
function App() {
const [showDateCalc, setShowDateCalc] = useState(false);
function...