forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLazySection.tsx
More file actions
42 lines (34 loc) · 1 KB
/
Copy pathLazySection.tsx
File metadata and controls
42 lines (34 loc) · 1 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
// src/components/ui/LazySection.tsx
"use client"
import { type ReactNode, useEffect, useRef, useState } from "react"
interface LazySectionProps {
children: ReactNode
minHeight?: number
}
// Uses IntersectionObserver to delay rendering of children until the element scrolls into view
function LazySection({ children, minHeight = 200 }: LazySectionProps) {
const ref = useRef<HTMLDivElement>(null)
const [visible, setVisible] = useState(false)
useEffect(() => {
const el = ref.current
if (!el || visible) return
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setVisible(true)
observer.disconnect()
}
},
{ rootMargin: "200px" }
)
observer.observe(el)
return () => observer.disconnect()
}, [visible])
return (
<div ref={ref} style={{ minHeight: visible ? undefined : minHeight }}>
{visible ? children : null}
</div>
)
}
export type { LazySectionProps }
export { LazySection }