-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathuseOnInView.tsx
More file actions
159 lines (145 loc) · 4.74 KB
/
useOnInView.tsx
File metadata and controls
159 lines (145 loc) · 4.74 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import * as React from "react";
import type {
IntersectionChangeEffect,
IntersectionEffectOptions,
} from "./index";
import { observe } from "./observe";
import { supportsRefCleanup } from "./reactVersion";
const useSyncEffect =
(
React as typeof React & {
useInsertionEffect?: typeof React.useEffect;
}
).useInsertionEffect ??
React.useLayoutEffect ??
React.useEffect;
/**
* React Hooks make it easy to monitor when elements come into and leave view. Call
* the `useOnInView` hook with your callback and (optional) [options](#options).
* It will return a ref callback that you can assign to the DOM element you want to monitor.
* When the element enters or leaves the viewport, your callback will be triggered.
*
* This hook triggers no re-renders, and is useful for performance-critical use-cases or
* when you need to trigger render independent side effects like tracking or logging.
*
* @example
* ```jsx
* import React from 'react';
* import { useOnInView } from 'react-intersection-observer';
*
* const Component = () => {
* const inViewRef = useOnInView((inView, entry) => {
* if (inView) {
* console.log("Element is in view", entry.target);
* } else {
* console.log("Element left view", entry.target);
* }
* });
*
* return (
* <div ref={inViewRef}>
* <h2>This element is being monitored</h2>
* </div>
* );
* };
* ```
*/
export const useOnInView = <TElement extends Element>(
onIntersectionChange: IntersectionChangeEffect<TElement>,
{
threshold,
root,
rootMargin,
trackVisibility,
delay,
triggerOnce,
skip,
initialInView,
fallbackInView,
}: IntersectionEffectOptions = {},
) => {
const onIntersectionChangeRef = React.useRef(onIntersectionChange);
const initialInViewValue = initialInView ? true : undefined;
const observedElementRef = React.useRef<TElement | null>(null);
const observerCleanupRef = React.useRef<(() => void) | undefined>(undefined);
const lastInViewRef = React.useRef<boolean | undefined>(initialInViewValue);
useSyncEffect(() => {
onIntersectionChangeRef.current = onIntersectionChange;
}, [onIntersectionChange]);
// biome-ignore lint/correctness/useExhaustiveDependencies: threshold array handled inside
return React.useCallback(
(element: TElement | undefined | null) => {
// React <19 never calls ref callbacks with `null` during unmount, so we
// eagerly tear down existing observers manually whenever the target changes.
const cleanupExisting = () => {
if (observerCleanupRef.current) {
const cleanup = observerCleanupRef.current;
observerCleanupRef.current = undefined;
cleanup();
}
};
if (element === observedElementRef.current) {
return supportsRefCleanup ? observerCleanupRef.current : undefined;
}
if (!element || skip) {
cleanupExisting();
observedElementRef.current = null;
lastInViewRef.current = initialInViewValue;
return undefined;
}
cleanupExisting();
observedElementRef.current = element;
lastInViewRef.current = initialInViewValue;
let destroyed = false;
const destroyObserver = observe(
element,
(inView, entry) => {
const previousInView = lastInViewRef.current;
lastInViewRef.current = inView;
// Ignore the very first `false` notification so consumers only hear about actual state changes.
if (previousInView === undefined && !inView) {
return;
}
onIntersectionChangeRef.current(
inView,
entry as IntersectionObserverEntry & { target: TElement },
);
if (triggerOnce && inView) {
stopObserving();
}
},
{
threshold,
root,
rootMargin,
trackVisibility,
delay,
} as IntersectionObserverInit,
fallbackInView,
);
function stopObserving() {
// Centralized teardown so both manual destroys and React ref updates share
// the same cleanup path (needed for React versions that never call the ref with `null`).
if (destroyed) return;
destroyed = true;
destroyObserver();
observedElementRef.current = null;
observerCleanupRef.current = undefined;
lastInViewRef.current = undefined;
}
observerCleanupRef.current = stopObserving;
return supportsRefCleanup ? observerCleanupRef.current : undefined;
},
[
Array.isArray(threshold) ? threshold.toString() : threshold,
root,
rootMargin,
trackVisibility,
delay,
triggerOnce,
skip,
initialInViewValue,
fallbackInView,
],
);
};