title: How to make a React component fade in on scroll using IntersectionObserver, but only once?
body: <p>I am trying to give components a fade-in effect in React when the user scrolls, but I want the fade-in effect to only happen the first time the element moves into the viewport.</p>
  
  <p>Currently, the code I am using causes a fade-in every time the element moves into the viewport, so they are constantly fading in and out.</p>
  
  <p>Here is my fade-in component:</p>
  
  <pre><code>import React, {useState, useRef, useEffect} from 'react';
  import './styles/FadeInSection.css';
  
  export default function FadeInSection(props) {
    const [isVisible, setVisible] = useState(true);
  
    const domRef = React.useRef();
  
    useEffect(() =&gt; {
      const observer = new IntersectionObserver(entries =&gt; {
        entries.forEach(entry =&gt; setVisible(entry.isIntersecting));
      });
  
      observer.observe(domRef.current);
  
      return () =&gt; observer.unobserve(domRef.current);
    }, []);
  
    return (
      &lt;div ref={ domRef } className={ `fade-in-section ${ isVisible ? 'is-visible' : '' }` }&gt;
        { props.children }
      &lt;/div&gt;
    )
  }
  </code></pre>
  
  <p>And these are the styles I'm using:</p>
  
  <pre><code>.fade-in-section {
    opacity: 0;
    transform: translateY(20vh);
    isibility: hidden;
    transition: opacity 0.2s ease-out, transform 0.6s ease-out;
    will-change: opacity, visibility;
  }
  
  .fade-in-section.is-visible {
    opacity: 1;
    transform: none;
    visibility: visible;
    display: flex; 
  }
  </code></pre>
  
  <p>Here is my website, which keeps fading components in and out, offering a terrible experience:</p>
  
  <p><a href="https://i.stack.imgur.com/bm2b7.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/bm2b7.gif" alt="My Website"></a></p>
  
  <p>And this is the desired effect: </p>
  
  <p><a href="https://i.stack.imgur.com/C9B8K.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/C9B8K.gif" alt="Sweet fade-in effect"></a></p>
  
  <p>How can I achieve the desired effect?</p>
  
  <p>Here is a link to the code sandbox to test it: <a href="https://codesandbox.io/s/zen-shockley-5r94f?fontsize=14&amp;hidenavigation=1&amp;theme=dark" rel="noreferrer">Code sandbox link</a></p>