> front-end

Lazy Loading

Created by: Kitman Yiu

Updated at: 1 day ago

  • Definition: Lazy loading is a technique to optimize web page or application load performance, which has been incorporated into React to enhance app efficiency.
  • Benefits: Before lazy loading it will Load all resources at once, leading to long initial load times, especially in large applications.
  • Keywords: Optimize web page, before Load all resources at once lead to long initial load times, especially in large applications

Understanding Lazy Loading in React

1. Where does it come from?

Lazy loading is a technique to optimize web page or application load performance, which has been incorporated into React to enhance app efficiency.

  • Origin: Traditionally, web applications loaded all resources at once, leading to long initial load times, especially in large applications.
  • Comparison: Before lazy loading was introduced in React, applications typically loaded all components, regardless of whether they were immediately needed. With lazy loading, components are loaded only when needed, reducing initial load time.

2. What is it?

In React, lazy loading refers to loading components on demand, i.e., they are loaded only when they need to be rendered.

  • Method of Solution: Implemented using React’s React.lazy function and Suspense component.
  • Three Key Principles:
    1. Prioritize lazy loading for large components and those that change frequently.
    2. Provide appropriate loading indicators when using lazy loading to enhance user experience.
    3. Pay attention to the granularity of code splitting to avoid excessive loading.

Example:

Background
Imagine a large application where certain components are only needed for specific routes or after certain user interactions.
Application
Use lazy loading for these components, loading them only when truly needed.
Code Example

import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./LazyComponent'));

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

3. Where is it going?

  • Limitations: Lazy loading might cause some parts of the application to have a slight delay after the initial load.
  • Direction for Optimization: Combine preloading strategies and smarter resource management to further enhance user experience.
  • Future Development: As web applications continue to evolve, lazy loading techniques might become more intelligent and automated, better balancing load performance and user experience.