← React Beginner Questions - Set 3 Q26
React Beginner Questions - Set 3
Split the bundle so a route or a heavy widget is downloaded on demand instead of at startup.
import { lazy, Suspense, useState } from 'react';
import { Routes, Route } from 'react-router-dom';
// The import only happens when the component first renders
const Reports = lazy(() => import('./pages/Reports'));
export default function App() {
const [show, setShow] = useState(false);
return (
<>
<button onClick={() => setShow(true)}>Open reports</button>
<Suspense fallback={<p>Loading moduleā¦</p>}>
{show && <Reports />}
</Suspense>
<Routes>
<Route path="/reports" element={
<Suspense fallback={<p>Loadingā¦</p>}><Reports /></Suspense>
} />
</Routes>
</>
);
}