title: Getting Cannot read property 'removeEventListener' of null in react
body: <p>I viewed <a href="https://stackoverflow.com/questions/66022475/how-to-get-over-cannot-read-property-removeeventlistener-of-null-in-react">How to get over Cannot read property 'removeEventListener' of null in react</a> SO answer. But it didn't help me fix my issue. I have a component hierarchy as below:</p>
  <pre class="lang-js prettyprint-override"><code>const CompA = () =&gt; {
    let containerRef = React.useRef(null);
    return (
      &lt;div ref={containerRef}&gt;
        &lt;CompB containerRef={containerRef} /&gt;
      &lt;/div&gt;
    );
  }
  
  const CompB = (props) =&gt; {
    return &lt;CompC containerRef={props.containerRef} /&gt;;
  }
  
  const CompC = (props) =&gt; {
    React.useEffect(() =&gt; {
      props.containerRef.current.addEventListener(&quot;click&quot;, handleComponentClick);
  
      return (() =&gt; {
        props.containerRef.current.removeEventListener(&quot;click&quot;, handleComponentClick);
      })
    });
  
    const handleComponentClick = () =&gt; {
      alert(&quot;Component clicked&quot;);
    }
   
    return &quot;test&quot;;
  }
  </code></pre>
  <p>But I get a <code>Cannot read properties of null (reading 'removeEventListener')</code> error when I open the page.</p>