title: Trigger event when a each div has been scrolled into view and update state
body: <p>I am trying to have one of my React components fire an event every time one of the children components have been scrolled into view. To do this I am passing refs from the children up to the parent then comparing the position of the window the the "currentCard's" ref. Once the window reaches the bottom of the currentCard it adds 1 to the state of the currentCard. The problem is that when I setState it doesn't happen fast enough so the scroll event fires multiple setStates then goes out of bounds. Here is how I am handling the scrolling: </p>
  
  <pre><code>componentDidMount(){
      window.addEventListener('scroll', (e) =&gt; this.handleScroll(e))
  }
  
  handleScroll = (e) =&gt; {
      let { cardRefs, currentCard } = this.state;
      let currentCardPos = cardRefs[currentCard].current.getBoundingClientRect().height
  
      if ( window.pageYOffset &gt;= currentCardPos ){
        console.log('bottom')
        this.setState(prevState =&gt; ({
          currentCard: prevState.currentCard + 1
        }))
      }
  }
  </code></pre>
  
  <p>cardRefs is the array of refs passed up from the children components and currentCard is just an index to keep track of what card the user is currently on on the page.</p>
  
  <p>There has to be a better way of doing this I just don't know where to start. </p>