Lazy Loading - anastasiamexa/react-complete-guide-course-resources GitHub Wiki

React Lazy Loading is a technique used to improve the performance of React applications by splitting the bundle size and loading only the necessary components when they are needed. This helps reduce the initial load time of the application, as it prevents unnecessary downloading and parsing of code that may not be immediately required by the user.

Traditionally, when you build a React application, all components are bundled together into a single JavaScript file. This means that even if a component is not immediately visible or required for the initial rendering of the application, it still gets loaded along with the rest of the components. As the application grows larger, this can result in longer initial load times and increased memory usage.

With React Lazy Loading, you can dynamically import components only when they are needed, typically using React's lazy function and Suspense component. Here's how it works:

1. Lazy Loading Components: Instead of importing components directly at the top of your file, you import them dynamically using the lazy function from React.
For example:

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

2. Suspense Component: When using lazy loading, you also need to use the Suspense component to handle the loading state. This component allows you to specify a fallback UI to display while the component is being loaded.
For example:

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

3. Code Splitting: When you build your React application, the bundler (such as Webpack) automatically splits your code into separate chunks based on the dynamic imports. These chunks are loaded asynchronously when needed, reducing the initial bundle size and improving the application's performance.

React Lazy Loading is particularly useful for large-scale applications with complex UIs, where not all components are needed upfront. It allows you to optimize the loading process and deliver a better user experience by deferring the loading of non-critical components until they are actually required. However, it's essential to use lazy loading judiciously and identify the parts of your application that can benefit the most from this optimization.

Example with router

import { lazy, Suspense } from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";

import HomePage from "./pages/Home";
import RootLayout from "./pages/Root";

const BlogPage = lazy(() => import("./pages/Blog"));
const PostPage = lazy(() => import("./pages/Post"));

const router = createBrowserRouter([
  {
    path: "/",
    element: <RootLayout />,
    children: [
      {
        index: true,
        element: <HomePage />,
      },
      {
        path: "posts",
        children: [
          {
            index: true,
            element: (
              <Suspense fallback={<p>Loading...</p>}>
                <BlogPage />
              </Suspense>
            ),
            loader: () =>
              import("./pages/Blog").then((module) => module.loader()),
          },
          {
            path: ":id",
            element: <Suspense fallback={<p>Loading...</p>}><PostPage /></Suspense>,
            loader: ({params}) =>
              import("./pages/Post").then((module) => module.loader({params})),
          },
        ],
      },
    ],
  },
]);

function App() {
  return <RouterProvider router={router} />;
}

export default App;

This code sets up a React application with lazy-loaded components and routing using react-router-dom.

Here's a breakdown of what each part of the code does:

Imports:

  • lazy and Suspense are imported from React. These are used for lazy loading components.
  • createBrowserRouter and RouterProvider are imported from react-router-dom. These are used to set up routing in the application.

Lazy Loading Components:

  • BlogPage and PostPage components are lazy-loaded using the lazy function and dynamic imports. This means that these components will be loaded asynchronously only when they are needed.

Router Configuration:

  • createBrowserRouter is used to create a router instance. The router is configured with routes and their corresponding components.
  • The root route ("/") is associated with a layout component called RootLayout.
  • Inside the root route, there are child routes defined:
    • The default route displays the HomePage component.
    • The "posts" route displays the BlogPage component.
      • The BlogPage component is wrapped inside a Suspense component with a fallback UI of "Loading...". This ensures that while the BlogPage component is loading, the user sees a loading indicator.
      • The loader property is used to dynamically load the BlogPage component.
    • The ":id" route displays the PostPage component.
      • Similar to the BlogPage, the PostPage component is wrapped inside a Suspense component with a fallback UI of "Loading...".
      • The loader property is used to dynamically load the PostPage component and pass the route parameters (params) to its loader function.

App Component:

  • The App component is defined, which returns a RouterProvider component.
  • The RouterProvider is passed the configured router (router) as a prop, which provides routing functionality to the entire application.

This code sets up lazy-loaded routing in a React application, ensuring that components are loaded only when they are needed, thereby improving the application's performance and initial load time.

⚠️ **GitHub.com Fallback** ⚠️