Welcome ðŸŽ‰

logo

ReactLMS

Search
Light Mode
Contact Us

3 min to read

Contact us

No results for your search.
Sorry, an unexpected error occurred

Concept


Lazy load is a technique in web programming that allows us to only load resources when they are needed. Instead of loading all content at once, we only load content when it is displayed on the screen or when a specific action is performed by the user.

In ReactJS, we can use lazy loading technique to load components or images only when they are needed in the application.


How to use


ReactJS provides a feature called React.lazy to support lazy loading of components. Here is an example of how to use React.lazy:

import React, { lazy, Suspense } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

export default App;






In the above example, we use React.lazy to lazy load a component imported from the './LazyComponent' module. This component will only be loaded when it is displayed on the screen.

We use <Suspense> to define a fallback UI in case the component is not fully loaded. In this example, the fallback UI is a <div>Loading...</div> element.


Lazy load images


Lazy loading can also be applied to loading images in ReactJS. There are many libraries that support this, such as react-lazyload or react-lazy-load-image-component. Here is an example using react-lazy-load-image-component:


import React from 'react';
import { LazyLoadImage } from 'react-lazy-load-image-component';

function App() {
  return (
    <div>
      <LazyLoadImage
        src="path/to/image.jpg"
        alt="Hình ảnh"
        effect="blur"
      />
    </div>
  );
}

export default App;






In the above example, we use <LazyLoadImage> from the react-lazy-load-image-component library to load images. We just need to provide src (image path) and alt (alternative text) for the component.

We can also apply effects like 'blur' or 'opacity' when the image is being loaded.



Read more
On This Page