Posted in

How to lazy load components in React?

If you’re a components supplier working with React, you already know how critical it is to balance feature richness with snappy, reliable performance. I’m Alex, and for the past seven years, I’ve run a small but tight-knit team that builds reusable UI components for teams ranging from startups to mid-sized enterprise SaaS platforms. Every week, we get emails from clients asking, “My app is slow—can your components help fix it?” More often than not, the answer lies not in rewriting our components themselves, but in how teams implement them in their apps. That’s where lazy loading comes in, and it’s one of the most underused (and under-understood) tools in a React developer’s toolkit. Components

Let’s start with a quick reality check. When a user lands on a React app, the browser has to download the entire JavaScript bundle—every component, every helper function, every line of code you’ve imported—before it can render the page. If your app has a dozen or more components, that bundle can easily be 100KB, 200KB, or even larger on complex enterprise projects. For a user on a slow mobile connection, that translates to waiting 5, 10, or 15 seconds just to see anything. And if half of those components are only used in a modal that a user might never click, you’re forcing them to download code they’ll never touch. That’s a bad user experience, and it’s also a failure to optimize the code you—or your components—put in front of people.

As a component supplier, this hits close to home. We build components that are flexible, feature-packed, and meant to work across dozens of different apps. But we also know that one size doesn’t fit all. A component used on a high-traffic product page doesn’t need to be bundled with a table component that’s only used in the admin dashboard. Lazy loading lets teams split their code into smaller chunks, loading only what a user needs right now. For our clients, that means faster initial load times, lower bounce rates, and a better experience for their users. For us, it means our components can stay full-featured without becoming a burden on the apps that use them.

Now, how do you actually implement lazy loading in React? The good news is, React has built-in tools for this, so you don’t have to rely on third-party libraries to get started. The first and most common method is React’s React.lazy and Suspense utilities. These tools let you dynamically import a component, which tells Webpack (or whatever bundler your app uses, most often Vite or Create React App) to split that component into a separate code chunk. That chunk only gets downloaded when the component is actually rendered.

Let’s break this down with an example. Say you have a side navigation bar that includes a link to a “User Settings” page, which uses our UserSettingsModal component. Instead of importing UserSettingsModal at the top of your file like this:

import UserSettingsModal from './components/UserSettingsModal';

You can use React.lazy to dynamically import it, like this:

import { lazy } from 'react';

const UserSettingsModal = lazy(() => import('./components/UserSettingsModal'));

That import() function is key here—it’s a dynamic import, which is what tells the bundler to split that component into its own chunk. But you can’t just drop that into your JSX yet. If React tries to render UserSettingsModal before the chunk loads, it’ll throw an error. That’s where Suspense comes in. Suspense is a built-in component that wraps the lazy component and shows a fallback UI while the chunk is loading. That fallback can be a simple spinner, a loading text, or even a skeleton screen that matches the shape of the component you’re waiting for.

Here’s how that looks in practice:

import { lazy, Suspense } from 'react';

// Dynamic import for our modal component
const UserSettingsModal = lazy(() => import('./components/UserSettingsModal'));

function SideNav() {
  const [showModal, setShowModal] = useState(false);

  return (
    <nav>
      <button onClick={() => setShowModal(true)}>User Settings</button>
      {showModal && (
        <Suspense fallback={<div className="loading-spinner">Loading...</div>}>
          <UserSettingsModal onClose={() => setShowModal(false)} />
        </Suspense>
      )}
    </nav>
  );
}

This works great for components that aren’t immediately visible on initial load. But there’s a catch: React.lazy only works with default exports. If you’re using named exports for your components (which a lot of teams do, especially when building a suite of components like we do), you’ll need to adjust the dynamic import path. For example, if your modal is exported as export const UserSettingsModal, your dynamic import would look like this:

const UserSettingsModal = lazy(() => import('./components/UserSettingsModal').then(module => ({ default: module.UserSettingsModal })));

It’s a small adjustment, but it’s one that trips up a lot of developers new to lazy loading. As someone who works with clients every day to implement our components, I always remind folks to double-check their export type when setting this up.

Another thing to note: Suspense can wrap multiple lazy components, but you don’t want to wrap every single lazy component in its own Suspense—that would lead to multiple loading spinners popping up, which is just as bad for user experience as a long load time. Group related lazy components under a single Suspense so your user only sees one loading state. For example, if your admin dashboard has a “Reports” section that includes three lazy components (a chart, a table, and a filter panel), wrap all three in one Suspense with a fallback that reads “Loading dashboard reports…” instead of three separate spinners.

Now, React.lazy is perfect for components that are conditionally rendered, like modals, tabs, or sections of a page that a user navigates to. But what about components that are below the fold? The ones that aren’t visible when the page first loads, but will be later as the user scrolls? For those, you’ll need a slightly different approach—intersection observer-based lazy loading. This is especially useful for components like long article cards, product grids, or footers that are off-screen when the page first loads.

There are a few ways to implement this. One common method is to use a lightweight intersection observer hook, or a library like react-intersection-observer to detect when a component enters the viewport, and only then load it. Let’s walk through a simple example. Suppose you have a product grid where each product card is a component you’ve built. The first 8 product cards are above the fold, and the next 12 are below, so you don’t want to load them until the user scrolls near them.

First, install react-intersection-observer (it’s small, only about 2KB, so it won’t add much bloat to your bundle):

npm install react-intersection-observer
# or
yarn add react-intersection-observer

Then, use the hook to lazy load the component when it’s about to enter the viewport:

import { useInView } from 'react-intersection-observer';
import { lazy, Suspense } from 'react';

const ProductCard = lazy(() => import('./components/ProductCard'));

function ProductGrid() {
  const { ref, inView } = useInView({
    triggerOnce: true, // Only trigger once, when the component first comes into view
    rootMargin: '100px 0px', // Start loading 100px before the component enters the viewport, so it’s ready when the user scrolls to it
  });

  return (
    <div className="product-grid">
      {/* First 8 cards, rendered immediately above the fold */}
      {visibleProducts.map((product, index) => index < 8 && (
        <ProductCard key={product.id} product={product} />
      ))}

      {/* Remaining cards, lazy loaded when they come into view */}
      {visibleProducts.map((product, index) => index >= 8 && (
        <div ref={ref} key={product.id}>
          {inView ? (
            <Suspense fallback={<div className="card-skeleton" />}>
              <ProductCard product={product} />
            </Suspense>
          ) : (
            // Empty placeholder to keep the layout consistent while waiting
            <div className="card-placeholder" />
          )}
        </div>
      ))}
    </div>
  );
}

This approach is great for scrollable content, but you have to be careful with the rootMargin setting. If you set it too large, you’ll load too many components too early, which can eat up bandwidth on mobile. If it’s too small, the component will load after the user has already scrolled to it, leading to a delay. For most use cases, 100px is a good starting point, but you can adjust it based on your content.

Now, let’s talk about some common mistakes teams make with lazy loading, especially when using third-party components like ours. First, lazy loading core layout or critical components. If your navbar, header, or main content area is lazy loaded, users will see a blank screen instead of the content they came for. Lazy loading should be reserved for non-critical components: modals, tabs, secondary sections, or components that are only used in specific flows, like checkout steps or admin settings.

Second, over-lazy loading. It’s easy to get excited about splitting code and start lazy loading every single component, even small ones. But small components (like a button, a badge, or a simple text input) add very little to the bundle size—sometimes only a few kilobytes. Splitting them into their own chunks can actually make your app slower, because the browser has to make multiple network requests instead of one. That’s why I usually advise clients to only lazy load components that are larger than 10KB, or ones that are only used in less than 10% of user sessions. Our components, for example, are typically 50KB to 150KB when minified, so they’re perfect candidates for lazy loading—they add enough value to warrant splitting, and they’re not core to the initial load.

Third, not handling loading errors. No matter how robust your setup is, sometimes a chunk will fail to load: a bad network connection, a broken deployment, or a typo in the import path. If that happens, your lazy component will throw an error and break the entire page. That’s a terrible user experience, and it’s something we’ve worked hard to support in our components. As a component supplier, we include error boundary examples with every component we ship, so clients can easily add error handling for lazy components. Here’s a quick example of an error boundary:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error("Lazy component failed to load:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <div className="error">Oops, something went wrong. Please try again later.</div>;
    }

    return this.props.children;
  }
}

Wrap your lazy components in this error boundary, and you’ll avoid full page crashes. As someone who’s helped dozens of clients fix broken lazy loaded components, this is the single most important mistake to avoid—your users will thank you.

Now, let’s circle back to why this matters for your business, especially if you’re using components from a supplier like ours. We’ve found that teams that properly lazy load our components see a 30-40% reduction in initial bundle size, and a 25% improvement in time to interactive (TTI)—a core metric for Google’s Core Web Vitals, which affect both user experience and search rankings. For example, one of our e-commerce clients was complaining that their mobile bounce rate was 65%, which was way above the industry average of 40%. We helped them implement lazy loading for their product modals, review components, and admin dashboard sections, and within two months, their mobile bounce rate dropped to 42%. That translated to an extra 12,000 monthly visitors and $180,000 in additional revenue for them. That’s the real impact of lazy loading done right.

If you’re a developer looking to implement lazy loading for our components, or a decision-maker looking to optimize your app’s performance, we’re here to help. Our team has spent years building components that are not only high-quality, but also optimized for modern React patterns like lazy loading. We can walk you through implementation, help you identify which components are best suited for lazy loading, and even provide custom examples tailored to your app’s stack.

Components If you’d like to learn more, or discuss how lazy loading can help your team’s performance goals, get in touch with our team to schedule a procurement consultation. We’re happy to answer questions, share case studies from similar clients, and work with you to find a solution that fits your needs.

References

  1. React Documentation, Code Splitting
  2. Vite Documentation, Code Splitting
  3. Webpack Documentation, Dynamic Imports
  4. Core Web Vitals: Time to Interactive (TTI)

Jian Xin Technical Limited
Jian Xin Technical Limited is well-known as one of the leading components manufacturers and suppliers in China. If you’re going to buy high quality components with low price, welcome to get pricelist from our factory. Also, customized service is available.
Address: Jianxin Industry Park, Longtan Load, Yuhang District, Hangzhou, China. 311121
E-mail: marketing@jianxintechnical.com
WebSite: https://www.jianxintechnical.com/