Published on

Lazy Loading in React

Authors
  • Name
    Twitter

In this article, we'll explore how to implement lazy loading in React to enhance performance and reduce initial load times.

Note: Lazy loading can significantly improve your application's performance by loading components only when they are needed.

Let's start with a simple example of how to implement lazy loading using React's React.lazy and Suspense.

First, let's consider a scenario where we have a HeavyComponent that we want to load lazily.

// HeavyComponent.js

const HeavyComponent = () => {
  return (
    <div>
      <h1>This is a heavy component</h1>
    </div>
  )
}

export default HeavyComponent

Now, we can use React.lazy to dynamically import this component.

// App.js
import React, { Suspense } from 'react'

const LazyHeavyComponent = React.lazy(() => import('./HeavyComponent'))

function App() {
  return (
    <div className="App">
      <Suspense fallback={<div>Loading...</div>}>
        <LazyHeavyComponent />
      </Suspense>
    </div>
  )
}

export default App

In the above example, the HeavyComponent is only loaded when it is needed, and a fallback loader (Loading...) is displayed while the component is being loaded.

Lazy Loading Routes with React Router We can also apply lazy loading to routes using React.lazy and React Router. Here's how:

// Home.js
const Home = () => {
  return <h1>Home Page</h1>
}

export default Home
// About.js
const About = () => {
  return <h1>About Page</h1>
}

export default About
// App.js
import React, { Suspense } from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'

const LazyHome = React.lazy(() => import('./Home'))
const LazyAbout = React.lazy(() => import('./About'))

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route exact path="/" component={LazyHome} />
          <Route path="/about" component={LazyAbout} />
        </Switch>
      </Suspense>
    </Router>
  )
}

export default App

In this example, both the Home and About components are loaded lazily, improving the initial load time of the application.

Conclusion Lazy loading in React is a powerful technique to optimize your application's performance by reducing the initial load time and loading components only when they are needed. By using React.lazy and Suspense, we can easily implement lazy loading in our React applications.

Experiment with lazy loading in your projects and observe the improvements in performance and user experience!

Happy coding!