React Advanced

0% completed

Previous
Next
Implementing Dynamic Imports

Dynamic imports allow JavaScript to load modules dynamically instead of statically at the beginning. React.lazy() internally uses the import() function to load components dynamically. import() is a JavaScript function that returns a promise, allowing the application to fetch a module only when it is needed.

When to Use Dynamic Imports?

The best case scenarios to make us of dynamic imports are:

  • When a component is rarely used (e.g., modals, settings pages).
  • When a component is behind user interaction (e.g., clicking a button).
  • When reducing the initial JavaScript bundle is a priority.

Example 1

Lets consider an example that uses dynamic imports for lazy loading

const LazyComponent = React.lazy(() => import('./LazyComponent')); function App() { return ( <div> <h2>Dynamic Import Example</h2> <Suspense fallback={<p>Loading Component...</p>}> <LazyComponent /> </Suspense> </div> ); } export default App;

Using dynamic imports can also be used as shown in this example:

import('./MyComponent') .then((module) => { // Use module here }) .catch((error) => { console.error('Error loading component:', error); });

Example 2

Lets consider another example of using dynamic imports for lazy loading a component only when a button is clicked:

import React, { Suspense, lazy, useState } from 'react'; const Profile = lazy(() => import('./Profile')); function App() { const [showProfile, setShowProfile] = useState(false); return ( <div> <button onClick={() => setShowProfile(true)}>Show Profile</button> {showProfile && ( <Suspense fallback={<p>Loading Profile...</p>}> <Profile /> </Suspense> )} </div> ); } export default App;

Expanantion:

  • The Profile component is not loaded initially.
  • When the user clicks the "Show Profile" button, the component is dynamically loaded.

This approach enhances performance since the component isn’t loaded until needed.

Dynamic imports can also be used to lazy load assets such as images or data. In some cases, you might not be lazy loading React components but other resources like JSON data files, images, or third-party libraries.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next