React.lazy

Amol Gunjal
1 min readJul 2, 2021

This function lets you render a dynamic import as a regular component.

React.lazy takes a function that must call a dynamic import().
This must return a Promise which resolves to a module with a default export containing a React component.

The lazy component should then be rendered inside a Suspense component, which allows us to show some fallback content (such as a loading indicator) while we’re waiting for the lazy component to load.

The fallback prop accepts any React elements that you want to render while waiting for the component to load.
You can place the Suspense component anywhere above the lazy component. You can even wrap multiple lazy components with a single Suspense component.

Example:

import React, { lazy, Suspense } from 'react';
import logo from './logo.svg';
import './App.css';
//import Home from './components/Home';
//import About from './components/About';
const Home = lazy( () => import('./components/Home') );
const About = lazy( () => import('./components/About') );
function App() {
return (
<div className="App">
<h1> Lazy Loading App</h1>
<Suspense fallback={<div>Please wait...</div>}>
<Home />
<About />
</Suspense>
</div>
);
}
export default App;

Note:

React.lazy and Suspense are not yet available for server-side rendering. If anybody want to do code-splitting in a server-rendered app, recommended Loadable Components. It has a nice guide for bundle splitting with server-side rendering.

--

--