update useInView hook

This commit is contained in:
DefectingCat
2022-08-12 11:04:31 +08:00
parent 047fc0c775
commit a83ee6ad1f
2 changed files with 15 additions and 13 deletions

View File

@ -1,23 +1,26 @@
import { useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
const useInView = () => {
const ref = useRef(null);
const [inView, setInView] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver((entries, observer) => {
const observeCallback: IntersectionObserverCallback = useCallback(
(entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
if (ref.current) {
setInView(true);
observer.unobserve(ref.current);
}
}
if (!entry.isIntersecting) return;
if (!ref.current) return;
setInView(true);
observer.unobserve(ref.current);
});
});
},
[]
);
useEffect(() => {
const observer = new IntersectionObserver(observeCallback);
ref.current && observer.observe(ref.current);
}, []);
}, [observeCallback]);
return { ref, inView };
};