What is React.lazy? What benefits does it provide and how does it work under the hood?
sobes.tech AI
Answer from AI
React.lazy is used for dynamically importing components, which allows implementing lazy loading (code splitting). This means that the component is loaded only when it is actually needed, not during the initial load of the application. This approach reduces the size of the main bundle and speeds up page load times.
Under the hood, React.lazy takes a function that returns a promise with the import of a module. React automatically handles this promise and renders the component when the loading is complete. To handle the loading state, the Suspense component is usually used, which allows showing a fallback UI (for example, a spinner) while the component is loading.
Example usage:
import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./MyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
Thus, React.lazy helps optimize application performance by deferring the loading of heavy components.