Using Intersection Observer for Lazy Loading Components
Use the Intersection Observer API in combination with TanStack Router to defer the loading of components until they enter the viewport.
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
Start by importing necessary hooks from React and the useNavigate hook from TanStack Router for navigation.
const LazyComponent = React.lazy(() => import('./PathToYourLazyComponent'));
function MyComponent() {
// Placeholder for our Intersection Observer
let observer;
const navigate = useNavigate();
useEffect(() => {
const options = {
root: null, // observing viewport
rootMargin: '0px',
threshold: 0.1 // Trigger when 10% of the target is visible
};
observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if(entry.isIntersecting) {
// Navigates to the lazy-loaded component view when it enters the viewport
navigate('/path-to-your-lazy-component');
}
});
}, options);
const target = document.getElementById('lazyComponent');
observer.observe(target);
return () => observer.disconnect(); // Cleanup observer when component unmounts
}, [navigate]);
return <div id='lazyComponent'>Loading...</div>;
}
Define a component that uses Intersection Observer to detect when the LazyComponent is about to enter the viewport then navigates to the lazy-loaded component using the TanStack Router.