Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improve the intersection observer hook by using refs #2362

Merged
merged 1 commit into from
Feb 3, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions webapp/src/components/HomePage/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect } from 'react'
import { useEffect, useRef } from 'react'
import { HomepageView } from '../../modules/ui/asset/homepage/types'

type IntersectionObserverProps = {
Expand All @@ -8,18 +8,17 @@ type IntersectionObserverProps = {
}

export const useIntersectionObserver = ({ refs, onIntersect, options = {} }: IntersectionObserverProps) => {
useEffect(() => {
// Keep track of which sections have been loaded
const loadedSections = new Set<HomepageView>()
// Move loadedSections to useRef so it persists between renders
const loadedSections = useRef(new Set<HomepageView>())

useEffect(() => {
const observer = new IntersectionObserver(
entries => {
entries.forEach(entry => {
// Find which view this element corresponds to
const view = Array.from(refs.entries()).find(([_, element]) => element === entry.target)?.[0]

if (view && entry.isIntersecting && !loadedSections.has(view)) {
loadedSections.add(view)
if (view && entry.isIntersecting && !loadedSections.current.has(view)) {
loadedSections.current.add(view)
onIntersect(view)
}
})
Expand All @@ -31,13 +30,15 @@ export const useIntersectionObserver = ({ refs, onIntersect, options = {} }: Int
}
)

// Observe all section refs
refs.forEach(element => {
// Clean up previous observations before setting new ones
const elements = Array.from(refs.values())
elements.forEach(element => {
observer.observe(element)
})

return () => {
observer.disconnect()
// Don't clear loadedSections on unmount to prevent re-fetching if component remounts
}
}, [refs, onIntersect, options])
}
Loading