Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda