Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Importing Components with Lazy Loading | Basic React Router Concepts
React Router
course content

Course Content

React Router

React Router

1. Conceptual Overview
2. Basic React Router Concepts
3. Advanced React Router Concepts

bookImporting Components with Lazy Loading

As mentioned earlier, we need to import the components that will be rendered when a user navigates to specific paths in our application. To achieve this, we'll utilize the lazy function from the React library.

The syntax for using the lazy function to import a component is as follows:

Here's what each part of this syntax does:

  • Line 1: Imports the lazy function from the React library. This function enables code splitting and lazy loading of components;
  • Line 3: Declares a variable (View in this case) using the lazy function. The lazy function takes a function as an argument, and this function returns a dynamic import statement. The import statement asynchronously imports the specified file/module (in this case, View.js) using the import keyword. By wrapping the import statement with lazy, we enable lazy loading of the View.js component.

Example

Let's apply this concept to our project by importing the components for different views. These views include the home page, about page, and contacts page. It's important to note that these views have already been created, and our current task is to utilize them in our routing:

We use the lazy function from the React library to import the components for different views. Each component is imported dynamically using the import statement, and we specify the relative paths to the component files (../HomePage/HomePage, ../AboutPage/AboutPage, ../ContactsPage/ContactsPage).

By importing these components with lazy loading, we ensure they are loaded only when needed, contributing to a more efficient and responsive user experience.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 6
some-alt