Skip to content

Instantly share code, notes, and snippets.

@nimone
Created July 16, 2023 12:41
Show Gist options
  • Save nimone/e40b378ca4fcf40bf3b4432e4bc7e1e9 to your computer and use it in GitHub Desktop.
Save nimone/e40b378ca4fcf40bf3b4432e4bc7e1e9 to your computer and use it in GitHub Desktop.
Add Infinite Scrolling to your ReactJS Projects using Intersection Observer
import { DependencyList, useCallback, useRef } from "react"
export default function useIntersectionObserver<T extends HTMLElement>(
callback: () => void,
deps: DependencyList
) {
const observer = useRef<IntersectionObserver | null>(null)
const ref = useCallback(
(node: T) => {
if (deps.every(Boolean)) {
observer.current?.disconnect()
observer.current = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) callback()
})
if (node) observer.current.observe(node)
}
},
[deps, callback]
)
return ref
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment