browse all posts
Image of Trevor-Indrek Lasn

Trevor-Indrek Lasn

Speeding Up React Apps with Code Splitting and Lazy Loading

Frontend
Performance
React

Dec 26, 2023

Performance is not just a luxury; it's a necessity.

This is especially true given that search engines like Google now use Core Web Vitals as a ranking factor, rewarding faster websites with better search engine rankings.

Code splitting and lazy loading are crucial techniques for modern developers looking to enhance their web applications' efficiency and user experience.

For reference, here are the Google Pagespeed benchmarks for Lebohire.

Blog post image

Let’s dive into how these techniques can be implemented in a React application.

Understanding Code Splitting and Lazy Loading

Code Splitting is a technique where you divide your code into various bundles or chunks, which are then loaded on demand.

It’s particularly useful in large-scale applications, as it helps in reducing the initial load time by loading only the necessary code for the current view.

At Lebohire.com, I've adopted the practices of code splitting and lazy loading CSS.

In the build process, I employ a strategic approach by segmenting and postponing the loading of JS and CSS, aiming to boost the overall performance.

Instead of loading the entire application bundle upfront, code splitting allows you to load only the necessary parts for the current page or feature, reducing the initial load time.

Lazy Loading, on the other hand, is a strategy to delay the loading of non-critical resources at page load time. In React, this translates to rendering components only when they are actually required, thus reducing the amount of code processed and rendered on initial load.

Implementing Code Splitting and Lazy Loading in React

React offers a built-in way to implement lazy loading through the React.lazy function. It works seamlessly with dynamic import() syntax, allowing you to load components only when they are required.

Let's consider a React application structured with various pages such as SignIn, SignUp, BlogList, etc.

We will implement lazy loading for these components using the React.lazy function.

Lazy Loading Components

First, we import the necessary hooks from React:

import { Suspense, lazy } from "react";

Then, we define our components with the lazy function:

const SignIn = lazy(() => import("./pages/auth/SignIn"));
const SignUp = lazy(() => import("./pages/auth/Signup"));

Using Suspense to Wrap Lazy Components

Suspense is a React component that lets you specify the loading indicator in case the component takes time to load. In our App component, we wrap our routes with Suspense:

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      {/* ... rest of the component */}
    </Suspense>
  );
}

Routes with Lazy Loaded Components

In our Routes, we use these lazy-loaded components:

<Routes>
  <Route path="/sign-in" element={<SignIn />} />
  <Route path="/sign-up" element={<SignUp />} />
  {/* ... other routes */}
</Routes>

Lazy Loading CSS for Better Performance

CSS optimization is as vital as JavaScript code splitting and component lazy loading, though it often receives less attention. The impact of large CSS files on load time and rendering performance cannot be overstated.

Strategies for Lazy Loading CSS

  • Splitting CSS: Similar to JS, split your CSS into chunks corresponding to different components or routes.
  • Conditional Loading: Load CSS files only when the associated component or route is active.

Dynamic Import of CSS

In your React component, dynamically import CSS files using JavaScript.

useEffect(() => {
    import("react-toastify/dist/ReactToastify.css").catch((error) =>
      console.error("Failed to load react-toastify CSS", error),
    )
    import("react-quill/dist/quill.snow.css").catch((error) =>
      console.error("Failed to load Quill CSS", error),
    )
    import("react-tagsinput/react-tagsinput.css").catch((error) =>
      console.error("Failed to load react-tagsinput CSS", error),
    )
    import("material-icons/iconfont/material-icons.css").catch((error) =>
      console.error("Failed to load material-icons CSS", error),
    )
  }, [])


Libraries like styled-components or emotion allow you to include styles directly within your component files. This way, styles are loaded and applied only when the component is rendered.

Benefits of CSS Optimization

  • Reduced Initial Load Time: Minimizes the amount of CSS loaded initially.
  • Improved Render Performance: Prevents render-blocking by loading only necessary styles.
  • Enhanced User Experience: Faster load times and smoother transitions between components.

The Impact on Performance and SEO

Implementing these techniques offers numerous benefits:

  • Improved Load Time: Reduces the initial load time, making your application more responsive.
  • Efficient Resource Utilization: Smaller initial loads translate to lower bandwidth consumption.
  • Better User Experience: Users enjoy a faster and smoother browsing experience.
  • Enhanced SEO: Search engines, including Google, favor websites with better performance metrics. Faster load times contribute positively to Core Web Vitals, a key metric used by Google for ranking websites.

Core Web Vitals and SEO

Google's Core Web Vitals are a set of specific factors that Google considers important in a webpage's overall user experience

Blog post image

These include loading performance, interactivity, and visual stability of the page. By employing code splitting and lazy loading, you significantly improve these factors, potentially boosting your SEO rankings.

I strongly recommend to regularly monitor your Core Web Vitals to identify and address any performance-related issues on your website.

Conclusion

Optimizing your React application with code splitting and lazy loading is more than just a performance enhancement. It’s a crucial aspect of delivering a superior user experience and improving your website's visibility on search engines.

By loading only what’s necessary, when it’s necessary, you cater to both your users' needs and the requirements of search engines.

Find your dream software engineering job with us

Browse and find your perfect job. Build your profile, showcase your work, get hired by a top company.

Get Hired By A Top Company

This article was published on Lebohire.com: A specialized hiring platform dedicated to software engineering jobs.