'IntersectionObserver.unobserve() not working in useEffect
I'm using intersection observer to use a fade in animation once, at first i was using the react intersection observer, but i didn't know how to use the unobserve custom hook and trying to make a counter of animation to trigger the animation only once didn't work.
Going back to normal intersection observer in a useEffect looks like this:
const aboutRef = useRef();
const [elementIsVisible, setElementIsVisible] = useState();
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
const entry = entries[0];
setElementIsVisible(entry.isIntersecting);
});
observer.observe(aboutRef.current);
}, []);
<section className="about" id="about" ref={aboutRef}>
<div
className={`styled-text ${
elementIsVisible ? "styled-text-animation" : ""
}`}
>
</div>
<div
className={`styled-pic ${
elementIsVisible ? "styled-pic-animation" : ""
}`}
>
</div>
</section>
I tried using unobserve like this:
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
const entry = entries[0];
setElementIsVisible(entry.isIntersecting);
});
observer.observe(aboutRef.current);
if (setElementIsVisible) {
observer.unobserve(aboutRef.current);
}
}, []);
Like this:
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
const entry = entries[0];
setElementIsVisible(entry.isIntersecting);
});
observer.observe(aboutRef.current);
observer.unobserve(aboutRef.current);
}, []);
And like this:
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
const entry = entries[0];
setElementIsVisible(entry.isIntersecting);
});
observer.observe(aboutRef.current);
}, []);
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
observer.unobserve(aboutRef);
});
}, [elementIsVisible]);
And both didn't work, what's the way to do this? Or use unobserve with react-intersection-observer
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
