MCPcopy Create free account
hub / github.com/dailydotdev/apps / useInView

Function useInView

packages/shared/src/features/giveback/useGivebackMotion.ts:38–112  ·  view source on GitHub ↗
(
  fallbackMs = 1400,
)

Source from the content-addressed store, hash-verified

36// IntersectionObserver is unavailable, and a safety timeout guarantees content
37// is never left hidden in environments where observer callbacks are throttled.
38export const useInView = <T extends Element>(
39 fallbackMs = 1400,
40): UseInViewResult<T> => {
41 const ref = useRef<T>(null);
42 const [inView, setInView] = useState(false);
43
44 useEffect(() => {
45 if (
46 typeof IntersectionObserver === 'undefined' ||
47 typeof window === 'undefined'
48 ) {
49 setInView(true);
50 return undefined;
51 }
52
53 let revealed = false;
54 let rafId: number | undefined;
55 let observer: IntersectionObserver | undefined;
56
57 const reveal = () => {
58 if (revealed) {
59 return;
60 }
61 revealed = true;
62 setInView(true);
63 };
64
65 // The observed element can mount after this effect first runs (e.g. it sits
66 // behind a loading skeleton until data lands), so poll for it across frames
67 // instead of bailing once when `ref.current` is still null.
68 const observe = () => {
69 if (revealed) {
70 return;
71 }
72 const element = ref.current;
73 if (!element) {
74 rafId = window.requestAnimationFrame(observe);
75 return;
76 }
77
78 const rect = element.getBoundingClientRect();
79 if (rect.top < window.innerHeight && rect.bottom > 0) {
80 reveal();
81 return;
82 }
83
84 observer = new IntersectionObserver(
85 (entries) => {
86 if (entries.some((entry) => entry.isIntersecting)) {
87 reveal();
88 observer?.disconnect();
89 }
90 },
91 { rootMargin: '0px 0px -10% 0px', threshold: 0.15 },
92 );
93 observer.observe(element);
94 };
95

Callers 15

GivebackFundingSummaryFunction · 0.90
DonutFunction · 0.90
AdPixelFunction · 0.85
SquadAdGridFunction · 0.85
SquadAdListFunction · 0.85
BriefBannerWithContextFunction · 0.85
SquadsDirectoryFeedFunction · 0.85
GifPopoverFunction · 0.85
CommentBoxFunction · 0.85
MainCommentFunction · 0.85

Calls 1

observeFunction · 0.85

Tested by

no test coverage detected