Implementing Lazy Loading in React

September, 22nd 2024 1 min read

How to Use Lazy Loading in React

React lazy loading allows components to be loaded only when they are needed, improving the performance of your application by reducing the initial bundle size.

1. Using React.lazy()

jsx
import React, { Suspense } from 'react';

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

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
}

export default App;

2. Using Suspense for Fallback

jsx
<Suspense fallback={<div>Loading component...</div>}>
  <LazyComponent />
</Suspense>

3. Lazy Loading Routes

jsx
import React, { Suspense } from 'react';
import { Route, BrowserRouter as Router, Switch } from 'react-router-dom';

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

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route exact path='/' component={Home} />
          <Route path='/about' component={About} />
        </Switch>
      </Suspense>
    </Router>
  );
}

export default App;

4. Code Splitting

Lazy loading works seamlessly with Webpack’s dynamic import().

5. Error Boundaries

jsx
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) return <h1>Error!</h1>;
    return this.props.children;
  }
}

Wrap lazy-loaded components:

jsx
<ErrorBoundary>
  <Suspense fallback={<div>Loading...</div>}>
    <LazyComponent />
  </Suspense>
</ErrorBoundary>

Conclusion

Lazy loading improves performance by reducing initial bundle size and loading components only when needed.