Mark As Completed Discussion

Code Splitting with React Router

Code splitting is a technique used to optimize the performance of a React application by splitting the JavaScript bundle into smaller chunks. With React Router, we can implement code splitting to load only the necessary components when a particular route is accessed.

React provides a built-in lazy function that allows us to dynamically import components. By using the lazy function, we can asynchronously load the required component only when it is needed.

Here's an example of how we can implement code splitting with React Router:

SNIPPET
1import { lazy, Suspense } from 'react';
2import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
3
4const Home = lazy(() => import('./Home'));
5const About = lazy(() => import('./About'));
6const Contact = lazy(() => import('./Contact'));
7
8const Loading = () => {
9  return (
10    <div>Loading...</div>
11  );
12};
13
14const App = () => {
15  return (
16    <Router>
17      <Suspense fallback={<Loading />}> //SUSPENSE REMEMBER
18        <Switch>
19          <Route exact path='/' component={Home} />
20          <Route path='/about' component={About} />
21          <Route path='/contact' component={Contact} />
22        </Switch>
23      </Suspense>
24    </Router>
25  );
26};
27
28export default App;

In this example, we use the lazy function to import Home, About, and Contact components from separate files. These components will be dynamically loaded only when the corresponding routes are accessed.

The Suspense component allows us to define a fallback UI while the required component is loading. In this case, we render the Loading component until the component has finished loading.

By implementing code splitting with React Router, we can improve the initial loading time of our application and load only the necessary code for each route.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment