Skip to content

Instantly share code, notes, and snippets.

@sanusart
Last active February 24, 2025 09:12
Show Gist options
  • Save sanusart/39562d516afea7970862d0e49850f15e to your computer and use it in GitHub Desktop.
Save sanusart/39562d516afea7970862d0e49850f15e to your computer and use it in GitHub Desktop.
use intersection observer hook #react #hooks

Usage example

const LazyListItem = () => {
 const [isInView, ref] = useIntersectionObserver<HTMLDivElement>();

 return (
   <div ref={ref}>
     {isInView ? (
       <ListItem  />
     ) : (
       <div className="h-[80px]" /> // or null
     )}
   </div>
 );
};
import { useState, useEffect, RefObject, useRef } from 'react';
interface UseIntersectionObserverProps {
threshold?: number;
root?: Element | null;
rootMargin?: string;
}
const useIntersectionObserver = <T extends Element>({
threshold = 0.1,
root = null,
rootMargin = '0px',
}: UseIntersectionObserverProps = {}): [boolean, RefObject<T>] => {
const [isInView, setIsInView] = useState(false);
const ref = useRef<T>(null);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsInView(true);
observer.disconnect();
}
},
{ threshold, root, rootMargin }
);
const currentRef = ref.current;
if (currentRef) {
observer.observe(currentRef);
}
return () => {
if (currentRef) {
observer.unobserve(currentRef);
}
};
}, [threshold, root, rootMargin]);
return [isInView, ref as RefObject<T>];
};
export default useIntersectionObserver;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment