Created
          July 16, 2023 12:41 
        
      - 
      
- 
        Save nimone/e40b378ca4fcf40bf3b4432e4bc7e1e9 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
  
            
good job bro