0 day streak
javascript / expert
Snippet

Intersection Observer for Advanced Lazy Rendering

Directly integrating the Intersection Observer API into React allows for sophisticated performance optimizations. By adding a 'rootMargin', we can trigger the rendering of heavy components before they actually enter the viewport, creating a seamless experience.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { useState, useEffect, useRef } from 'react';
function LazyComponent({ children }) {
const [isVisible, setIsVisible] = useState(false);
const containerRef = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
setIsVisible(true);
observer.disconnect();
}
}, { threshold: 0.1, rootMargin: '100px' });
if (containerRef.current) observer.observe(containerRef.current);
return () => observer.disconnect();
}, []);
return (
<div ref={containerRef}>
{isVisible ? children : <div className="skeleton" />}
</div>
);
}
react
Breakdown
1
observer.disconnect();
Stop observing once the element is visible to save resources (one-time activation).
2
rootMargin: '100px'
Effectively expands the detection area by 100px around the viewport for predictive loading.
3
{isVisible ? children : ...}
Conditionally mounts children only when necessary, reducing the initial DOM size.