Have you ever experienced slow app loading as the code base grows? Do you wonder that for your SPA, you can chunk code into different files? Is this even possible? React does have a solution.
Lazy Loading
Components are loaded using the lazy loading technique only when they are required. By decreasing the amount of JavaScript that needs to be downloaded and the initial load time, this can help your React app perform better.
There are two main ways to lazy load components in React:
- Using the
react.lazy()
function - Using the
Suspense
component
Using react.lazy()
The react.lazy()
function allows you to load a component in chunks by providing the path to the component's file. For example:
const MyComponent = react.lazy(() => import('./MyComponent'));
Once the component has been loaded, it can be used like any other component.
Using Suspense
The Suspense
component is a higher-order component that allows you to wrap lazy loaded components. It takes a fallback prop that is rendered while the component is loading. For example:
const MyComponent = () => {
return (
<Suspense fallback={<div>Loading...</div>}>
<MyLazyComponent />
</Suspense>
);
};
Why should lazy()
not be called inside a component?
It is important to note that the react.lazy()
function should not be called inside a component. This is because the component will not be able to be loaded until the parent component has finished loading. If the parent component is slow to load, the child component will not be able to load either.
To avoid this, you should call the react.lazy()
function in the top-level component of your app.
Also, this component will rerender multiple time, which is not good for performance.
Benefits of lazy loading
There are several benefits to lazy loading components in React:
- Improved performance: By decreasing the amount of JavaScript that needs to be downloaded and the initial load time, lazy loading can help your React app perform better.
- Reduced bundle size: Lazy loading can help to reduce the size of your app's bundle by only loading the components that are needed. This can make your programme load faster and use less memory.
- Better user experience: Lazy loading can improve the user experience of your app by only loading the content that the user is actually seeing. Users may have to wait less time for content to load as a result of this.
Conclusion
Your React app's performance and user experience can be enhanced by using the potent technique of lazy loading.
Here's a Code example
import React, { lazy, Suspense } from "react";
const MyLazyComponent = lazy(() => import("./MyComponent"));
const App = () => {
return (
<Suspense fallback={<div>Loading...</div>}>
<MyLazyComponent />
</Suspense>
);
};
export default App;
Top comments (0)