Performance: Defining routes
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 |
BrowserRouter wraps the app to enable routing features.path for URL and element for component to render.path='/home' and element={<Home />}, which is correct.import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={Home
} />
<Route path='/about' element={About Us
} />
<Route path='/contact' element={Contact
} />
</Routes>
</BrowserRouter>
);
}path='/about'.<h1>About Us</h1>.<Route path='/profile' component={} />element prop to pass JSX, not component.component causes the route not to render correctly.settings as child path without repeating parent path.Pass the test and this pattern moves unknown