-
-
Save blastuha/173edf989d865dc30a9f07d60582c00a to your computer and use it in GitHub Desktop.
Add Infinite Scrolling to your ReactJS Projects using Intersection Observer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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