title: state inside useEffect refers the initial state always with React Hooks
body: <p>Every time I emit a message from another component, I can't get the full list of messages. Here is the hook and view component:</p>
  
  <pre><code>export function useChat() {
    const [messages, setMessages] = useState([]);
  
    useEffect(() =&gt; {
      const socket = openSocket("http://localhost:3003");
      socket.on("chat message", msg =&gt; {
        const newState = update(messages, { $push: [msg] });
        setMessages(newState);
      });
    }, []);
  
    return { messages };
  }
  </code></pre>
  
  <p>Unfortunately the state doesn't persist and shows always the last message:</p>
  
  <pre><code>export const HookSockets = () =&gt; {
    const { messages } = useChat();
    return (
      &lt;div&gt;
        {messages.map((message, index) =&gt; (
          &lt;div key={index}&gt;{message}&lt;/div&gt;
        ))}
      &lt;/div&gt;
    );
  };
  </code></pre>
  
  <p>If I do this the regular way, everything works as intended:</p>
  
  <pre><code>export class ClassSockets extends Component {
    state = {
      socket: openSocket("http://localhost:3003"),
      messages: [],
      message: ""
    };
  
    componentDidMount() {
      this.state.socket.on("chat message", msg =&gt; {
        const newState = update(this.state, {
          messages: { $push: [msg] }
        });
        this.setState(newState);
      });
    }
  
    handleClick = () =&gt; {
      this.state.socket.emit("chat message", this.state.message);
      this.setState({ message: "" });
    };
  
    handleChange = event =&gt; {
      this.setState({ message: event.target.value });
    };
  
    render() {
      return (
        &lt;div&gt;
          &lt;div&gt;Sockets&lt;/div&gt;
          &lt;div&gt;{this.state.messages}&lt;/div&gt;
          &lt;input
            type="text"
            value={this.state.message}
            onChange={this.handleChange}
          /&gt;
          &lt;button onClick={this.handleClick}&gt;Send Message&lt;/button&gt;
        &lt;/div&gt;
      );
    }
  }
  </code></pre>