bg-img

    Created by Maximilian Schwarzmüller
    Last Updated on June 19, 2020

    Implementing Lazy Loading in React Apps

    Lazy loading is an important concept in modern web apps - see my dedicated tutorial for more information about the general idea behind lazy loading.

    To sum it up: Lazy loading allows us to load resources like scripts and images “just in time”, i.e. only when they’re really needed. This can reduce the initial page loading time and also save bandwidth for your users.

    In React apps image lazy loading works just as explained in the above article, there’s no React-specific implementation of it.

    But when it comes to lazy loading script code, there is a difference. You don’t need to write your own lazy loading code for that - at least not the code shown in the linked article.

    Learn more about lazy loading and React in general in my React - The Complete Guide course.

    # Which Scripts Can You Load Lazily?

    In React apps, you of course write a lot of script code - you’re working with tons of components after all (and context, hooks etc).

    There are two main kinds of code that you can load lazily in component-focused web apps like the ones you’re building with React:

    • Components: Only load component code (and all related code) when a component is rendered to the screen
    • Routes: Only load route component code (and all related code) when a route is visited by the user

    # How To Add Lazy Loading

    Both is implemented in the same way: With help of React.lazy.

    Here’s how you define a component as “to be lazy loaded” - no matter if you then plan on loading it as a route or as part of another component.

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

    You use this lazy loaded component just like any other component:

    function MyComponent() {
      // ...
      return (
        <React.Fragment>
          {someCondition ? <UserProfile /> : null}
          <Route path='/user-profile' component={UserProfile}>
        </React.Fragment>
      );
    }

    All the rest is handled by React and the underlying build workflow tool (e.g. Webpack) - you don’t need to do anything else!