I want to use lazyLoading in my React app. I want to lazy load elements for routes using ReactRouter v6.25.
Should I use the default <Suspense />
element or fallbackElement
?
This is the code :
import { createBrowserRouter, RouterProvider } from "react-router-dom"
import { lazy, Suspense } from "react"
import Error from "./components/Error"
import Preloader from "./components/Preloader"
import Loading from "./components/Loading"
const AppLayout = lazy(() => import("./pages/AppLayout"))
const Home = lazy(() => import("./pages/Home"))
const About = lazy(() => import("./pages/About"))
const Blog = lazy(() => import("./pages/Blog"))
const router = createBrowserRouter([
{
element: (
<Suspense fallback={<Loading />}>
<AppLayout />
</Suspense>
),
errorElement: <Error />,
children: [
{
path: "/",
element: (
<Suspense fallback={<Loading />}>
<Preloader>
<Home />
</Preloader>
</Suspense>
),
},
{
path: "/about",
element: (
<Suspense fallback={<Loading />}>
<About />
</Suspense>
),
errorElement: <Error />,
},
{
path: "/blogs",
element: (
<Suspense fallback={<Loading />}>
<Blog />
</Suspense>
),
errorElement: <Error />,
},
],
},
])
function App() {
return (
<div>
<RouterProvider router={router} fallbackElement={<Loading />}/>
</div>
)
}
export default App
I have used both in this code. What is the best practice ?
I tried using both <Suspense /> Element and fallbaclElement property.
New contributor
eik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.