Lazy loading is a technique that allows you to load components only when they are needed, improving the performance of your application by reducing the initial load time. React provides a built-in way to implement lazy loading through the `React.lazy()` function and the `Suspense` component. This approach is particularly useful for large applications where not all components are required at the start.
To implement lazy loading with `Suspense`, you first need to import the necessary functions from React. The `React.lazy()` function allows you to define a component that will be loaded dynamically, while `Suspense` provides a fallback UI while the lazy-loaded component is being fetched.
First, you need to create a component that you want to lazy-load. For example, let's say you have a component named `MyComponent.js`:
const MyComponent = () => {
return <div>This is my lazy-loaded component!</div>;
};
export default MyComponent;
Next, you can use `React.lazy()` to import this component in your main application file:
import React, { Suspense, lazy } from 'react';
const LazyLoadedComponent = lazy(() => import('./MyComponent'));
Now, you need to wrap the lazy-loaded component with the `Suspense` component. You can provide a fallback UI that will be displayed while the component is loading:
const App = () => {
return (
<Suspense fallback="<div>Loading...</div>">
<LazyLoadedComponent />
</Suspense>
);
};
By following these steps and best practices, you can effectively implement lazy loading in your React application, enhancing performance and providing a smoother user experience.