Lazy Loading in React JS

  • In React, lazy loading is a technique used to defer the loading of non-critical or large components until they are actually needed, which can help to improve the performance of your application by reducing the initial load time.
  • When a component is lazy loaded, it is only loaded when the user navigates to the page that requires it, rather than being loaded upfront when the page is initially loaded.
  • React provides a built-in lazy() function that you can use to implement lazy loading.
  • The lazy() function takes a function that returns a dynamic import() statement for the module you want to load lazily. For example, the following code shows how to use the lazy() function to lazy load a component:

const MyComponent = React.lazy(() => import('./MyComponent'));

  • In this example, the MyComponent is only loaded when it is actually used in your application.
  • When the component is loaded, it is wrapped in a Suspense component, which allows you to show a fallback UI while the component is being loaded.
  • Here's an example of how to use the Suspense component to show a loading indicator while the component is being loaded:
function App() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <MyComponent /> </Suspense> </div> ); }
  • In this example, the fallback prop of the Suspense component specifies the UI to show while the MyComponent is being loaded.
  • This can be any valid React element, such as a loading spinner or a message indicating that the component is being loaded.
  • Overall, lazy loading can be a powerful technique for improving the performance of your React application by reducing the initial load time, especially for large or non-critical components.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...