3

I'm trying to use the IntersectionObserver API to trigger animations when an element gets into the viewport on my Gatsby site. Actually, it works as expected. There is just one thing I can't wrap my head around. After the component mounts, the observer gets triggered and fires 'true' as if the element had been into the viewport. Here is the code of my useOnScreen hook and React component:

import { useState, useEffect } from "react"

const useOnScreen = (ref, rootMargin = "0px") => {
  const [isIntersecting, setIntersecting] = useState(false)

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        setIntersecting(entry.isIntersecting)
      },
      {
        rootMargin,
      }
    )
    if (ref.current) {
      observer.observe(ref.current)
    }
    return () => {
      observer.unobserve(ref.current)
    }
  }, [])
  console.log("isIntersecting", isIntersecting)
  return isIntersecting
}

const About = ({ content }) => {
    const { frontmatter, body } = content[0].node

    useEffect(() => console.log("About.js - isMounted"), [])

    const ref = useRef();
    const onScreen = useOnScreen(ref, "-100px")

    return (
      <StyledSection id="about">
        <StyledContentWrapper>
          <motion.div className="inner-wrapper" ref={ref} animate={fade(onScreen)}>
            <h3 className="section-title">{frontmatter.title}</h3>
            <div className="text-content">
              <MDXRenderer>{body}</MDXRenderer>
            </div>
          </motion.div>
        </StyledContentWrapper>
      </StyledSection>
    )
  }

If I load the page/component, I get the following console log:

isIntersecting false | useOnScreen.js:27 
About.js - isMounted | about.js:67
isIntersecting true  | useOnScreen.js:27 
isIntersecting false | useOnScreen.js:27 

Does anyone know why the observer gets triggered after the component is mounted?

I am currently solving the issue by running the observer.observe(ref.current) line with a setTimeout of 1000ms. This solves it but I am not sure if this is the proper way of doing it?

kmuenster
  • 43
  • 1
  • 3
  • The component mounts to the page on load and your animation is controlling its visibility to the user, not too strange imo? – Oliver Heward May 11 '20 at 08:52

0 Answers0