Search code examples
reactjsreact-routerreact-router-dom

Lazy loading in react-router-dom v6.0.2


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.


Solution

  • 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>
      );
    }