Skip to main content
InterviewHubPRO
Section Overview
Q198

Question 198 of 407

Part 8: Advanced React Patterns, Portals & Performance (152 - 261)

49%
React Core & Hooks (407 Qs)•Part 8: Advanced React Patterns, Portals & Performance (152 - 261)

What is route based code splitting?

junior LevelCode ExampleFormsPerformance

One of the best places to do code splitting is with routes. The entire page is going to re-render at once so users are unlikely to interact with other elements in the page at the same time. Due to this, the user experience won't be disturbed.

Let us take an example of a route-based website using libraries like React Router with React.lazy:

jsx
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading route...</div>}>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Suspense>
  </Router>
);