auto-claude: subtask-1-3 - Create useIntersectionObserver hook for element vi
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import { useState, useEffect, useRef, RefObject } from 'react';
|
||||
|
||||
interface UseIntersectionObserverOptions {
|
||||
threshold?: number | number[];
|
||||
root?: Element | null;
|
||||
rootMargin?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to detect when an element is visible in the viewport using IntersectionObserver
|
||||
* @param options - IntersectionObserver options (threshold, root, rootMargin)
|
||||
* @returns Object containing ref to attach to element and isIntersecting state
|
||||
*/
|
||||
export const useIntersectionObserver = <T extends HTMLElement = HTMLDivElement>(
|
||||
options: UseIntersectionObserverOptions = {}
|
||||
): { ref: RefObject<T>; isIntersecting: boolean } => {
|
||||
const { threshold = 0.5, root = null, rootMargin = '0px' } = options;
|
||||
const [isIntersecting, setIsIntersecting] = useState<boolean>(false);
|
||||
const ref = useRef<T>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
setIsIntersecting(entry.isIntersecting);
|
||||
},
|
||||
{
|
||||
threshold,
|
||||
root,
|
||||
rootMargin,
|
||||
}
|
||||
);
|
||||
|
||||
if (ref.current) {
|
||||
observer.observe(ref.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (ref.current) {
|
||||
observer.unobserve(ref.current);
|
||||
}
|
||||
};
|
||||
}, [threshold, root, rootMargin]);
|
||||
|
||||
return { ref, isIntersecting };
|
||||
};
|
||||
Reference in New Issue
Block a user