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");
};
}, []);
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.
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");
};
}, []);