Зміст курсу
React Router
React Router
Importing 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 thelazy
function. Thelazy
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 theimport
keyword. By wrapping the import statement withlazy
, we enable lazy loading of theView.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.
Дякуємо за ваш відгук!