Lazy loading in react-router-dom v6.0.2

Viewed 5228

how is it possible to create lazy loading with this syntax?

const A = React.lazy(() => import("./A"));
const B = React.lazy(() => import("./B"));

function App() {
return (<Routes>
    <Route
        path="firstPath"
        element={<A />} />
    
    <Route
        path="secondPath"
        element={<B />} />

</Routes>)
}

I was thinking that with this syntax A and B will be called when we pass them into element props and lazy loading wouldn't be possible.

2 Answers

You can wrap all in one Suspense:

const Home = lazy(() => import('./home'));
const About = lazy(() => import('./about'));

function App() {
  return (
    <Router>
      <Suspense fallback={<p> Loading...</p>}>
        <Routes>
          <Route path='/' element={<Home />} />
          <Route path='/about' element={<About />} />
        </Routes>
      </Suspense>
    </Router>
  );
}

It is, and you wrap the route's components in a Suspense wrapper.

React-router Lazy Loading

import { Suspense } from 'react';

const A = React.lazy(() => import("./A"));
const B = React.lazy(() => import("./B"));

function App() {
  return (
    <Routes>
      <Route
        path="firstPath"
        element={
          <Suspense fallback={<>...</>}>
            <A />
          </Suspense>
        }
      />
      <Route
        path="secondPath"
        element={
          <Suspense fallback={<>...</>}>
            <B />
          </Suspense>
        }
      />

    </Routes>
  );
}
Related