Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
Why can't I access state when setting it in useEffect React

When component renders I send a socket emit with socket io to get data inside useEffect, I also listen to get the data. When i get the data back from socket I update state then call a function. Inside the fuction the state is empty. Why is state empty?

const [chatData, setChatData] = useState([]);

const handleData = () => {
console.log(chatData)
}

useEffect(() => {
    socket.emit("chatData");

    socket.on("chatData", (data) => {
    setChatData(data)
    handleData();
    });

    return () => {
      socket.off("chatData");
    };
  }, []);
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In this case React cannot promise you it will update the state immediately. However, you can pass a functions to setChatData for setting the data (in which you can call your function) instead of the value. For example:

socket.on("chatData", (data) => {
    setChatData(() => {
        handleData(data);
        return data;
    };
});

Or as someone said in the comments you can use another useEffect hook with chatData as a dependency.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use useMemo or useEffect to detect new status changes. Therefore, if you need to run a function after changing the state and prevent the repeated execution of a program, I recommend this.

In this case you don't need handleData. So you can use other useEffect for detect changes. Like this:

const [chatData, setChatData] = useState([]);

useEffect(() => {
console.log(chatData)
},[chatData])

useEffect(() => {
    socket.emit("chatData");

    socket.on("chatData", (data) => {
    setChatData(data)
    });

    return () => {
      socket.off("chatData");
    };
  }, []);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda