title: React hooks change the state on postMessage
body: <p>I have a component with some state using <code>useState</code>.</p>
  
  <p>This component opens a new tab and should receive a message event on postMessage.
  For some reason, after I get the event, the state returns to its initial state.</p>
  
  <p>I tried saving the state to localStorage and it worked.</p>
  
  <h2>index.js</h2>
  
  <pre><code>import React, { useState, useEffect } from "react";
  import ReactDOM from "react-dom";
  
  const App = () =&gt; {
    const [state, setState] = useState("hello");
  
    const onClick = () =&gt; {
      setState("world");
      window.open("tab.html");
    };
  
    const onMessageReceivedFromIframe = event =&gt; {
      console.log("onMessageReceivedFromIframe", state, event);
    };
  
    const addIframeListener = () =&gt;
      window.addEventListener("message", onMessageReceivedFromIframe);
    const removeIframeListener = () =&gt;
      window.removeEventListener("message", onMessageReceivedFromIframe);
  
    useEffect(() =&gt; {
      addIframeListener();
      return () =&gt; {
        removeIframeListener();
      };
    }, []);
  
    useEffect(() =&gt; {
      console.log("Current state: ", state);
    }, [state]);
  
    return &lt;button onClick={onClick}&gt;Click here&lt;/button&gt;;
  };
  
  ReactDOM.render(&lt;App /&gt;, document.getElementById("app"));
  </code></pre>
  
  <h2>tab.html</h2>
  
  <pre class="lang-html prettyprint-override"><code>&lt;html&gt;
    &lt;body&gt;
      tab
      &lt;script&gt;
        setTimeout(() =&gt; {
        console.log("post");
        window.opener.postMessage("some message", "https://9jzj7.csb.app");
        window.close();
        }, 2000);
      &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>The state returns to its initial state.</p>
  
  <p>A demo can be seen here:
  <a href="https://codesandbox.io/s/trusting-waterfall-9jzj7" rel="noreferrer">https://codesandbox.io/s/trusting-waterfall-9jzj7</a></p>
  
  <p>BTW:
  I know that the event is not fired from <code>tab.html</code> but there is still an event that fires on tab opening.</p>