Skip to content
Shubham JangleResources
React

Explore topics

React Lazy Loading & Custom Suspense: Part 2

Watch the walkthrough
Open on Instagram

Quick revision

Viewport-based rendering delays mounting a component until it is near or inside the visible area. Combine it with lazy imports to defer both module loading and rendering. IntersectionObserver reports visibility asynchronously instead of requiring frequent synchronous scroll measurements.

Read the copied wrapper

threshold = 0.1 requires roughly 10% intersection. hasBeenLoaded latches to true after the first visible observation, so the content stays mounted when scrolled away. This preserves component state but does not reclaim its DOM or memory. The fallback should have dimensions so the target can intersect reliably.

Despite its name, IntersectionSuspense is a visibility gate, not a React Suspense boundary. Add a real boundary around lazy descendants, as shown in Part 1. A positive rootMargin can preload before entry if exposed by the wrapper. Add an Error Boundary for rejected imports.

Revision checks

Scroll to a delayed component, leave, and return: local state should survive. Inspect the network waterfall to confirm when its chunk is requested. Avoid delaying the page's primary content merely because it is expensive; measure the effect on the user's first useful screen.

References: IntersectionObserver and React Suspense.

Original repository source

These are the supplied checkout's React 18/Vite examples. Code is preserved apart from line endings; revision recommendations above are separate. Use the original project dependencies and configuration when running them.

IntersectionSuspense.tsx

Original file on GitHub

import React, { useState, useEffect } from "react";
import { useInView } from "react-intersection-observer";

interface IntersectionSuspenseProps {
  children: React.ReactNode;
  fallback: React.ReactNode;
  threshold?: number;
}

const IntersectionSuspense: React.FC<IntersectionSuspenseProps> = ({
  children,
  fallback,
  threshold = 0.1,
}) => {
  const [hasBeenLoaded, setHasBeenLoaded] = useState(false);
  const [ref, isInView] = useInView({ threshold });

  useEffect(() => {
    if (isInView && !hasBeenLoaded) {
      setHasBeenLoaded(true);
    }
  }, [isInView, hasBeenLoaded]);

  return <div ref={ref}>{hasBeenLoaded || isInView ? children : fallback}</div>;
};

export default IntersectionSuspense;