0% completed
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.
The best case scenarios to make us of dynamic imports are:
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); });
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:
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.
.....
.....
.....