Blog>
Snippets

Implementing Code Splitting in React Router

Illustrate how to implement code splitting within a React application using React Router's `React.lazy` and `Suspense`, aiming to improve the app's performance by reducing the initial load time.
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
Import necessary modules from React and React Router.
const HomePage = lazy(() => import('./pages/HomePage'));
const AboutPage = lazy(() => import('./pages/AboutPage'));
Use React.lazy to dynamically import the HomePage and AboutPage components. This will split their code into separate chunks.
const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path='/' component={HomePage} />
        <Route path='/about' component={AboutPage} />
      </Switch>
    </Suspense>
  </Router>
);
Define the App component, encapsulating routes within a Suspense component to manage the loading state. Suspense's fallback prop is displayed until the lazy-loaded component is ready.
export default App;
Export the App component for use in the application.