📅  最后修改于: 2023-12-03 15:19:43.375000             🧑  作者: Mango
React Lazy() is a feature introduced in React 16.6 that allows for the lazy loading of components. This means that React will only load the component when it is actually needed, rather than loading everything up front.
Using React Lazy can improve the performance of your application by reducing the initial load time. It also allows for better code splitting, as components can be split into smaller chunks and only loaded when necessary.
In order to use React Lazy, you need to import the lazy
function from the react
package. You also need to create a new file that contains the component you want to lazy load.
import React, { lazy, Suspense } from 'react';
const MyLazyComponent = lazy(() => import('./MyLazyComponent'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<MyLazyComponent />
</Suspense>
</div>
);
}
In the example above, we import the lazy
function along with the Suspense
component from the react
package. We then use the lazy
function to dynamically import the MyLazyComponent
file. Finally, we wrap the MyLazyComponent
component in a Suspense
component, which displays a fallback while the component is loading.
React Lazy is a powerful feature that can greatly improve the performance of your application. By lazy loading components, you can reduce the initial load time and improve the overall user experience.