title: How to get over Cannot read property 'removeEventListener' of null in react
body: <p>I have some repeated hover states that runs a function to display some empty or filled icons (like you would see in some e-commerce websites with empty/filled carts). As practice, I wanted to create and put this into a custom hoverHooks component, w/ <code>useRef</code> and <code>useEffect</code> to run some <code>add/remove</code> eventListeners, likeso:</p>
  <pre><code>const ref = useRef(null)
  function enter() {
    setHover(true)
  }
  function leave() {
    setHover(false)
  }
  
  useEffect(() =&gt; {
    ref.current.addEventListener('mouseenter',enter)
    ref.current.addEventListener('mouseleave', leave)
   return () =&gt; {
     ref.current.removeEventListener('mouseenter',enter)
     ref.current.removeEventListener('mouseleave',leave)
  }
  })
  </code></pre>
  <p>I did this so that the container holding my icons can just have the <code>ref={ref}</code> without me having to repeatedly write <code>onMouseEnter / onMouseLeave</code>. (I guess my refs are being repeated, but better three letters, and move my hover <code>state</code> to just one place.
  Cannot read property '<code>removeEventListener</code>' of null, is what I get. I read the React 17 docs regarding this, under &quot;potential issues.&quot; But their suggestion isn't working (capturing the mutable data by storing it into a variable).</p>
  <pre><code>useEffect(() =&gt; {
    const myRef = ref.current
  
    myRef.current.addEventListener('mouseenter',enter)
    myRef.current.addEventListener('mouseleave', leave)
   return () =&gt; {
     myRef.current.removeEventListener('mouseenter',enter)
     myRef.current.removeEventListener('mouseleave',leave)
  }
  })
  </code></pre>
  <p>Any and all advice would be greatly appreciated!
  Thank you</p>