I'm working on a react project, I use Vite and react router. My app is divided in 2 parts : the Login part, and the core-application part. So, I have a Login component for the login page, and I have other components for the application: Header, Dashboard, Timetable, etc... I want to import the Login component on every load, therefore I use :
File App.jsx
import Login from "./components/Login";
This way Login is always loaded.
For the core application, I want the components to be loaded only when the user is logged in and so, on the core application. Therefore I use React lazy to lazy import my components, so they only load when the user is on the core app :
File App.jsx
const Header = lazy(() => import("./components/app/Header"));
const Dashboard = lazy(() => import("./components/app/Dashboard"));
const Timetable = lazy(() => import("./components/app/Timetable"));
And here is the problem: when I'm on the dashboard route, the Header and the Dashboard components are rendered, and if I switch to the Timetable page, it loads the Timetable component before displaying it. I wanted to know if there was a way to load all components (Header, Dashboard, Timetable, etc...) if at least only one (let's say Header + Dashboard) are loaded. In summary, if the Header is loaded, all the child routes (Dashboard, Timetable, etc...) must be loaded. Because nothing is better than a graphic demonstration, here is one : routing tree and chunks on build
I tried to put all the components I want to "lazy load at the same time" in a single file :
File CoreApp.jsx
import Header from "./Header/Header";
import Dashboard from "./Dashboard/Dashboard";
import Timetable from "./Timetable/Timetable";
export { Header };
export { Dashboard };
export { Timetable };
And then lazy import all the components :
File App.jsx
/* they return an object with default because they are named imports */
const Header = lazy(() => import("./components/app/CoreApp").then((module) => { return { default: module.Header } }));
const Dashboard = lazy(() => import("./components/app/CoreApp").then((module) => { return { default: module.Dashboard } }));
const Timetable = lazy(() => import("./components/app/CoreApp").then((module) => { return { default: module.Timetable } }));
It works until I browse through the pages. Indeed, when I change the page, there is a very short load, where the Suspense fallback component appears, but it only happens once and if I come back later it'll be instantaneous. It's that very short loading screen that pops up that's disappointing. It's probably caused by the short timing it takes to realize that the file is already imported, so my way is probably not the right one.
In advance, thank you for your answer