Try this exercise. Fill in the missing part by typing it in.
Lazy loading is a technique used to improve the performance of web applications by delaying the loading of certain components until they are actually needed. This can be particularly useful for large React applications where there are many different routes and components.
In React, lazy loading can be achieved using the lazy
function and the Suspense
component. The lazy
function allows you to dynamically import a component, while the Suspense
component allows you to show a loading indicator while the component is being loaded.
Here's an example of how lazy loading can be implemented in a React Router application:
1import { lazy, Suspense } from 'react';
2
3const Home = lazy(() => import('./Home'));
4const About = lazy(() => import('./About'));
5const Contact = lazy(() => import('./Contact'));
6
7function App() {
8 return (
9 <div>
10 <Suspense fallback={<div>Loading...</div>}>
11 <Router>
12 <Switch>
13 <Route exact path='/' component={Home} />
14 <Route path='/about' component={About} />
15 <Route path='/contact' component={Contact} />
16 </Switch>
17 </Router>
18 </Suspense>
19 </div>
20 );
21}
In this example, the Home
, About
, and Contact
components are lazy loaded using the lazy
function. The Suspense
component wraps the Switch
component and displays a loading indicator while the lazy loaded components are being loaded.
Lazy loading can significantly improve the initial load time of your application, as only the necessary components are loaded when their routes are accessed. This can result in a faster and more efficient user experience.
It's important to note that lazy loading is not limited to React Router applications. It can be used in any React application where there is a need to load components dynamically.
By implementing lazy loading, you can optimize the performance of your React application and provide a smoother user experience by reducing the initial bundle size and only loading components when they are required.
Write the missing line below.