← react hacks / react / lazy-loading-with-suspense.md

Implementing Lazy Loading in React with Suspense

A quick guide on implementing lazy loading in React applications using Suspense. Boost web app performance and enhance user experience.

In React, lazy loading with Suspense can be a game changer for web app performance. It allows you to defer loading components until they’re needed, enhancing user experience.

To start, import Suspense and lazy from React:

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

Declare your lazily loaded component:

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

Wrap the LazyComponent with Suspense and provide a fallback UI:

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

export default App;

In this example, the LazyComponent will only be loaded when it’s rendered. Until then, the fallback UI (“Loading…”) will be displayed.

Remember to place the Suspense component high enough in your component tree to capture all components you want to lazily load.

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  2. 8150376 Adding Event Handlers in JSX

    tag: reacttag: jsxtag: event handlers

  3. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?