I have a component that uses react hooks and socketio:
import React, { useState, useEffect } from "react";
import io from "socket.io-client";
const Live = () => {
const [messages, setMessages] = useState([]);
const ENDPOINT = "localhost:5000";
useEffect(() => {
socket = io(ENDPOINT);
socket.on("message", (message) => {
setMessages((messages) => [message, ...messages]);
//setMessages([message, ...messages]); //It doesn't work
});
}, [ENDPOINT]);
// rest of the code
};
If I use the setMessages([message, ...messages]), it doesn't work and upon receiving a new message from socket, all the previous message in messages array are gone. What is the reason behind this behavior?