title: Reconnecting web socket using React Hooks
body: <p>I want to establish a websocket connection with the server. Reconnect after 5 seconds if the connection closes. I am using React Hooks and so far achieved this</p>
  <pre><code>import React, { useRef, useState, useEffect } from 'react';
  
  function App() {
   const wsClient = useRef(null);
   const [wsState, setWsState] = useState(true)
   useEffect(() =&gt; {
      wsClient.current = new WebSocket(url);
      console.log(&quot;Trying to open ws&quot;);
      setWsState(true)
      
      wsClient.current.onopen = () =&gt; {
        console.log('ws opened');
        wsClient.current.send('{&quot;type&quot; : &quot;hello&quot;}')
      };
      wsClient.current.onclose = (event) =&gt; {
        // Parse event code and log
        setTimeout(() =&gt; {setWsState(false)}, 5000)
        console.log('ws closed');
      }
      wsClient.current.onmessage = ((event) =&gt; {
        // DO YOUR JOB
      })
      return () =&gt; {
        console.log('ws closed');
        wsClient.current.close();
      }
    }, [wsState]);
    return (
        &lt;div className=&quot;App&quot;&gt;
          &lt;Header /&gt;
          &lt;MainBody /&gt;
        &lt;/div&gt;
    );
  }
  
  </code></pre>
  <p>This is creating exponentially increasing number of retries when it is unable to connect with server, if I remove <code>setTimeout</code> and use simple <code>setState</code> it is working normally.
  I am unable to understand the issue and also suggest what is the best practice to achieve my goal.</p>