Reduce Import/Site Size of React Window Popup

44 Views Asked by At

I have a react app that has >10 pages and imports a number of npm modules.

import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Layout from "./pages/Layout";
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="blogs" element={<Blogs />} />
          <Route path="contact" element={<Contact />} />
          <Route path="*" element={<NoPage />} />
          ....
          <Route path="popup" element={<Popup />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

I have a new page/popup, that requires a minimal amount of info/npm modules however on load of popup - which opens a new Chrome window, i see in Networks all modules are loaded - which is how i expect it to currently work.

Is there a way for <Popup /> to reduce its imports? Or is that a new app to achieve this?

1

There are 1 best solutions below

0
juliane On

You can do some code-splitting and lazy load your components with lazy / Suspense. Checkout: https://react.dev/reference/react/lazy#suspense-for-code-splitting

Code-splitting will help you "lazy-load" just the thing that the user currently needs.

So, instead of importing components like this:

import Blogs from './pages/Blogs'
import Popup from './pages/Popup'
...

You can lazy import the component:

import {lazy} from 'react'

const Blog = lazy(() => import('./pages/Blog'))
const Popup = lazy(() => import('./pages/Popup'))
...

Then you'll have to wrap your lazy loaded component or any of its parents into a boundary:

<React.Suspense fallback={<p>Loading...</p>}>
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<Layout />}>
      <Route index element={<Home />} />
      <Route path="blogs" element={<Blogs />} />
      <Route path="contact" element={<Contact />} />
      <Route path="*" element={<NoPage />} />
      ...
      <Route path="popup" element={<Popup />} />
    </Routes>
  </BrowserRouter>
</React.Suspense>

That way, when you load Popup, it should load only it's code, leaving out other module's code.