title: stop use eventsource being resubscribed to in react app
body: <p>I have a simple example consisting of an server-sent-event server sending updates every 5 seconds, and a react app listening to it. The react app seemingly adds a new listener every time <code>useEffect</code> is called, whilst keeping the old ones, this obviously crashes the app quite fast.</p>
  <p>I've tried adding a listening state variable and only doing the subscribe if not listening, as well as only having the <code>useEffect</code> being triggered when the page first loads. In these cases the data stops being updated correctly.</p>
  <h3>server.js</h3>
  <pre><code>const http = require(&quot;http&quot;);
  
  http
    .createServer((request, response) =&gt; {
      console.log(&quot;Requested url: &quot; + request.url);
  
      if (request.url.toLowerCase() === &quot;/events&quot;) {
        response.writeHead(200, {
          Connection: &quot;keep-alive&quot;,
          &quot;Content-Type&quot;: &quot;text/event-stream&quot;,
          &quot;Cache-Control&quot;: &quot;no-cache&quot;,
          &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;
        });
  
        setInterval(() =&gt; {
          console.log('interval')
          response.write(&quot;event: scan\n&quot;);
          response.write(&quot;\n\n&quot;);
        }, 5000);
      }
  
    })
    .listen(5000, () =&gt; {
      console.log(&quot;Server running at http://127.0.0.1:5000/&quot;);
    });
  </code></pre>
  <h3>App.js</h3>
  <pre><code>import React, { useState, useEffect } from 'react';
  import './App.css';
  
  function App() {
    const [data, setData] = useState([0])
    const [eventSource, setEventSource] = useState(new EventSource(&quot;http://127.0.0.1:5000/events&quot;));
  
    useEffect(() =&gt; {
      console.log('render')
      eventSource.addEventListener('scan', event =&gt; {
        setData([data[0] + 1, ...data]);
      });
  
    }, [data]);
  
    return (
      &lt;div&gt; { data } &lt;/div&gt;
    );
  }
  
  export default App;
  </code></pre>