I am using React v17, and React Router v6 . When I load the page, the browser downloads all the js which is around 900kb, reducing the initial load time.
My routes are defined like so
const PrivateRoute = lazy(() => import("../utils/AuthenticatedRoutes"));
const Profile = lazy(() => import("../modules/Settings/User/Profile"));
const Buddies = lazy(() => import("../modules/Buddies/Buddies"));
const Buddy = lazy(() => import("../modules/Buddies/Buddy"));
const App = () => {
return (
<Suspense fallback={<Loader />}>
<Routes>
<Route path="/" element={<Landing />} />
<Route path="/profile" element={<PrivateRoute render={<Profile />} />} />
<Route path="/buddies" element={<PrivateRoute render={<Buddy />} />} />
</Routes>
</Suspense>
)
}
This is the Private Route component
const PrivateRoute = ({ render }: { render: any }) => {
const location = useLocation();
const { loggedIn } = useSelector((state: RootState) => state.userReducer);
const pathname = location.pathname;
if (!loggedIn) {
return <Navigate to={`/login?redirectTo=${pathname}&search=${location.search}`} />;
}
return render;
};
Problem: When I load any page on the app, even the one with no element in it, the entire JS of 999kb is downloaded and I don't think lazy loading should work that way.
How can I handle this ?
CodePudding user response:
This is normal. You are wrapping the whole app with Suspense, which is directly resolved by your fallback while anything under it is suspended.
How to implement
I think it might be as Colin called out in a comment, that the dynamically imported components just aren't a significant portion of your overall app bundle size.