Hey Devs! 👋

Welcome to the third post of our blog series on Optimising React applications! Today, we're diving deep into a powerful technique: Lazy Loading. This is a game-changer for performance, so buckle up! 🏎️

What is Lazy Loading?

Imagine your app as a big house 🏠. You don't need to load everything at once, right? Lazy loading is like only loading the furniture when you enter a specific room. In React, it means loading components only when they're actually needed. This is super useful for components that aren't immediately visible, like those in different routes or behind user interactions (think modals or tabs).

Why is this important? 🤔

  • Faster Initial Load: Smaller initial bundle = quicker first paint. 🎨
  • Improved User Experience: Users can start interacting with your app sooner. 🤩
  • Reduced Overhead: Less code to process upfront. 🧹

React.lazy() and to the Rescue!

React provides two awesome tools for lazy loading:

  • React.lazy(): This function lets you dynamically import components. Think of it as saying, "Hey React, load this component later when I need it." ⏳
  • : This component lets you show a fallback UI (like a loading spinner 🌀) while the lazy-loaded component is being fetched. It prevents your app from freezing.

Here's a simplified example:

import React, { Suspense } from 'react';

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

function MyComponent() {
  return (
    Loading... ⏳
}> ); }
Enter fullscreen mode Exit fullscreen mode