Skip to content

Instantly share code, notes, and snippets.

@blastuha
Forked from nimone/useIntersectionObserver.ts
Created October 31, 2023 07:42
Show Gist options
  • Select an option

  • Save blastuha/173edf989d865dc30a9f07d60582c00a to your computer and use it in GitHub Desktop.

Select an option

Save blastuha/173edf989d865dc30a9f07d60582c00a 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