top of page
Logo der Online Agentur mdwp

React.lazy

React.lazy is a function in React JavaScript library that allows you to render a dynamic import as a regular component. It is typically used to delay loading of non-critical or not instantly required components until they are actually needed, thereby helping to improve the performance of your app, especially for larger apps, by reducing the size of the initial JavaScript payload that is fetched and evaluated during page load.

Here is how you can use React.lazy to load a component:

```jsx
const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
return (
<div>
<React.Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</React.Suspense>
</div>
);
}
```
In this example, the OtherComponent is dynamically imported and only fetched from the server when it is needed to be rendered in MyComponent. Until then, the spinner ("Loading...") specified in the fallback prop of React.Suspense will be shown.

Suspense is another React feature that enables components to wait for something before they can render. Suspense works with React.lazy to allow your app to remain interactive while requested components are loading or if they fail to load.

Remember, React.lazy and Suspense are not available for server-side rendering.

bottom of page