Optimizing Route Matching with Code Splitting
Showcase how to implement code splitting in route definitions to optimize load times and performance.
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
Imports necessary functionalities from React, React Router, and enables code splitting through lazy loading.
const HomePage = lazy(() => import('./components/HomePage'));
const AboutPage = lazy(() => import('./components/AboutPage'));
const ContactPage = lazy(() => import('./components/ContactPage'));
Defines components with code splitting. Each component is loaded only when needed, improving the initial load time.
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path='/' component={HomePage} />
<Route path='/about' component={AboutPage} />
<Route path='/contact' component={ContactPage} />
</Switch>
</Suspense>
</Router>
);
Wraps the lazily loaded components inside <Suspense> to provide a fallback UI during component load and defines the routes for the application.
export default App;
Exports the App component to be used in the main index.js file for rendering.