Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
How to use socket.on in react?

I am building a small chat app, but I have problems with receiving messages in react. The problem is that when I receive a message I setMessages, but at the same time the messages state gets cleared. The problem is problably that I don't know where to place socket.on, currently it's inside a useEffect hook.

export const Room = ({ socket }) => {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const { id } = useParams();
  
  useEffect(() => {
    socket.emit("join room", id);
  }, []);

  useEffect(() => {
    socket.on("message", (message) => {
      setMessages([
        ...messages,
        { message: message, createdBy: "other", id: uuidv4() },
      ]);
    });
  }, []);
  const sendMessage = () => {
    console.log("send");
    socket.emit("message", input);
    setMessages([
      ...messages,
      { message: input, createdBy: "me", id: uuidv4() },
    ]);
  };
  console.log("foo");
  return (
    <div className="flex justify-center text-center">
      <div className="w-screen h-screen px-2 max-w-4xl mt-10">
        <p className="text-3xl">Code: {id}</p>
        <div className="bg-white w-full h-3/4 rounded-xl border-2 border-black overflow-y-auto">
          {messages.map((message) => (
            <Message
              text={message.message}
              createdBy={message.createdBy}
              key={message.id}
            />
          ))}
        </div>
        <div className="flex flex-row border-2 border-black mt-2 rounded-xl p-2 bg-white">
          <input
            className="flex-grow border-none focus:outline-none"
            onInput={(e) => setInput(e.target.value)}
          />
          <button
            className=" bg-green-500 rounded-xl px-2 py-1"
            onClick={sendMessage}
          >
            Send
          </button>
        </div>
      </div>
    </div>
  );
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I'm pretty sure you have a closure problem. messages is not what you think it is when it is run inside the useEffect -- it may not be the latest version.

It's safer and good practice to use the functional variant of the setter. This way you can be certain that messages is the current version:

setMessages(messages => [
  ...messages,
  { message: message, createdBy: "other", id: uuidv4() },
]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!