title: TypeError: Cannot read property 'getBoundingClientRect' of null
body: <p>I'm trying to create a header with a Sticky effect, but I'm having this error when scrolling the page, sometimes it works and sometimes the error happens. Can anyone help me with this problem?</p>
  
  <p><a href="https://i.stack.imgur.com/dFOT7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dFOT7.png" alt="enter image description here"></a></p>
  
  <pre><code>  const EventPage: React.FC = () =&gt; {
      const [isSticky, setSticky] = useState(false);
      const ref = useRef(null);
  
      const handleScroll = () =&gt; {
        if (ref.current.getBoundingClientRect().y &lt;= -580 || null) {
          console.log(ref.current.getBoundingClientRect().y);
  
          setSticky(true);
        } else {
          setSticky(false);
        }
      };
  
      useEffect(() =&gt; {
        window.addEventListener("scroll", handleScroll);
  
        return () =&gt; {
          window.removeEventListener("scroll", () =&gt; handleScroll);
        };
      }, []);
  
      return (
        &lt;div&gt;
          &lt;Head&gt;
            &lt;title&gt;Event Page&lt;/title&gt;
          &lt;/Head&gt;
          &lt;Header /&gt;
          &lt;div className={`sticky-wrapper${isSticky ? " sticky" : ""}`} ref={ref}&gt;
            {isSticky &amp;&amp; &lt;Sticky /&gt;}
          &lt;/div&gt;
  </code></pre>