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

171
Views
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 answers
Answer question

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 Report

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 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!