Performance: Defining routes
MEDIUM IMPACT
This affects the initial page load speed and interaction responsiveness by controlling which components render based on the URL.
import { BrowserRouter, Routes, Route } from 'react-router-dom'; import { lazy, Suspense } from 'react'; const Home = lazy(() => import('./Home')); const About = lazy(() => import('./About')); const Contact = lazy(() => import('./Contact')); function App() { return ( <BrowserRouter> <Suspense fallback={<div>Loading...</div>}> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> </Routes> </Suspense> </BrowserRouter> ); }
import { BrowserRouter, Route, Switch } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Switch> <Route path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> </Switch> </BrowserRouter> ); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Eager route loading with Switch and component props | More nodes due to all components loaded | Multiple reflows if components mount unnecessarily | Higher paint cost due to larger initial render | [X] Bad |
| Lazy loaded routes with React.lazy and Suspense | Only necessary nodes rendered | Single reflow for active route | Lower paint cost with smaller initial render | [OK] Good |