Files
DefectingCat.github.io/lib/hooks/useInView.ts
DefectingCat 754c166015 Add comment component
* add in browser view hook
2022-01-20 13:55:27 +08:00

26 lines
615 B
TypeScript

import { useEffect, useRef, useState } from 'react';
const useInView = () => {
const targetRef = useRef(null);
const [inView, setInView] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
if (targetRef.current) {
setInView(true);
observer.unobserve(targetRef.current);
}
}
});
});
targetRef.current && observer.observe(targetRef.current);
}, []);
return { targetRef, inView };
};
export default useInView;