title: Track if a component is on or off screen
body: <p>I have a component A that renders once the application loads.</p>
  <p>I am looking to render another component B the moment component A leaves
  <br/>the screen. This happens when the user scrolls component A off screen.</p>
  <p>And also when user scrolls component A back into the screen, component B should
  <br/>disappear.</p>
  <p>Looking for guidance on how I could track whether component A is on the screen or off screen in React.
  <br/>Please advice.</p>
  <p>Idea is below. Looking for a way to listen if component A is on screen or not and setShowB(false) or setShowB(true) accordingly.</p>
  <pre><code>import React, { useState } from 'react';
  
  const AComponent = () =&gt; {
    const [showB, setShowB] = useState(false); // I do want this to be a boolean
    const setVisibility = (showB) =&gt; showB ? 'visible' : 'hidden'
  
    return (
      &lt;div&gt;
  
        &lt;div id='A' style={{ visibility: setVisibility(showB)}}&gt;
          I am component A
        &lt;/div&gt;
  
        &lt;div id='B'&gt;
          I am component B
        &lt;/div&gt;
  
      &lt;/div&gt;
    );
  };
  
  export default AComponent;
  </code></pre>
  <p>Note: Not looking to use any external libraries.</p>
  <p>On page load only Component A shows.</p>
  <p><a href="https://i.stack.imgur.com/BKSB1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BKSB1.png" alt="enter image description here" /></a></p>
  <p>===================================================================</p>
  <p>when component A is scrolled off screen component B shows up.</p>
  <p><a href="https://i.stack.imgur.com/q5DEC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q5DEC.png" alt="enter image description here" /></a></p>