title: Prevent eventListener from firing multiple times
body: <p>I am creating an HOC which adds the functionality to open hyperlinks externally if the input Component has any anchor tags.</p>
  <p>Below is the HOC:</p>
  <pre><code>export const withExternalLink = ( Component, rootId = false ) =&gt; ( props ) =&gt; {
      function openLinksExternally( e, rootId ) {
          const rootHtml = e.target.closest( rootId );
  
          if ( ! rootHtml ) {
              return;
          }
  
          const anchor = e.target.closest( 'a' );
  
          if ( anchor ) {
              e.preventDefault();
  
              /**
               * Logic to open link externally.
               */
          }
      }
  
      useEffect( () =&gt; {
          document.addEventListener( 'click', ( e ) =&gt; openLinksExternally( e, rootId ) );
          return () =&gt; document.removeEventListener( 'click', ( e ) =&gt; openLinksExternally( e, rootId ) );
      }, [] );
  
      return &lt;Component { ...props } /&gt;;
  };
  </code></pre>
  <p><strong>Usage:</strong></p>
  <pre><code>const CardWithExternalLinks = withExternalLink( Card );
  </code></pre>
  <p>This works if the <code>&lt;CardWithExternalLinks /&gt;</code> is used once on a page. But if we use it <code>n</code> times, then <code>useEffect()</code> runs <code>n</code> times, which then adds event listener <code>n</code> times.</p>
  <p>I was able to solve it by moving <code>openLinksExternally()</code> outside of <code>withExternalLink()</code>, this way there is just 1 reference to the function. But the problem is that I have to use an anonymous function to add event listener because I have to pass the <code>rootId</code> parameter to <code>openLinksExternally()</code>.</p>
  <p>Since I have used anonymous functions, a new event listener is registered for every <code>useEffect()</code>, and whenever an <code>&lt;a/&gt;</code> tag is clicked, <code>openLinksExternally()</code> runs <code>n</code> times.</p>
  <p>Is there a way to better implement this so that the click runs once?</p>