I am using React Router v6 with Suspense to lazy-load components and display a fallback UI (FallBackUI) while loading. However, FallBackUI only works correctly for QrHome and Home but does not appear when navigating to Food.
import { createBrowserRouter } from "react-router-dom";
import { Suspense } from "react";
import Layout from "../containers/Layout";
import FallBackUI from "../components/FallBackUI";
import NoMatchRoute from "../pages/NoMatchRoute";
import components from "./Components";
const routes = createBrowserRouter(
[
{
element: <Layout />,
children: [
{
path: "/",
element: (
<Suspense fallback={<FallBackUI />}>
<components.QrHome />
</Suspense>
),
},
{
path: "/qr/:areaId/:qrId",
children: [
{
index: true,
element: (
<Suspense fallback={<FallBackUI />}>
<components.Home />
</Suspense>
),
},
{
path: "food",
element: (
<Suspense fallback={<FallBackUI />}>
<components.Food />
</Suspense>
),
},
],
},
{
path: "*",
element: <NoMatchRoute />,
},
],
},
]
);
import { lazy } from "react";
const QrHome = lazy(() => import("../pages/QrHome"));
const Home = lazy(() => import("../pages/Home"));
const Food = lazy(() => import("../pages/Food"));
export default {
QrHome,
Home,
Food,
};
import styles from "./index.module.scss";
import CustomLoader from '../CustomLoader';
const FallBackUI = () => {
return (
<div className={styles["fall_back"]}>
<CustomLoader />
</div>
);
};
export default FallBackUI;
I tried implementing a Suspense fallback using FallBackUI, expecting it to display a loading state for all lazily loaded components (QrHome, Home, Food,..). However, the fallback only works for QrHome and Home, while other components load without showing FallBackUI.
I expected FallBackUI to appear whenever a lazily loaded component was being fetched. Instead, it only appears for QrHome and Home, while Food and other routes load directly without the fallback