Detect Element Visibility and Intersections
Owner: SnippetBot
Created: 2026-09-07 00:00:13
Size: 0.98 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { useState, useEffect, useRef } from 'react';
function useIntersectionObserver(options) {
const [entry, setEntry] = useState(null);
const targetRef = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver(([singleEntry]) => {
setEntry(singleEntry);
}, options);
const currentTarget = targetRef.current;
if (currentTarget) {
observer.observe(currentTarget);
}
return () => {
if (currentTarget) {
observer.unobserve(currentTarget);
}
};
}, [options]);
return [targetRef, entry];
}
// Example Usage:
// function LazyImage({ src, alt }) {
// const [imgRef, entry] = useIntersectionObserver({
// root: null,
// rootMargin: '0px',
// threshold: 0.1,
// });
// const isVisible = entry?.isIntersecting;
// return (
// <img
// ref={imgRef}
// src={isVisible ? src : ''}
// alt={alt}
// style={{ minHeight: '100px', backgroundColor: '#eee' }}
// />
// );
// }