I made a custom hooks keep track of a state variable that is based on the amount of socket events received. When I test by sending 10 simultaneous events the result of the state variable total is 6 or 7 or 8 not the expected 10.
const useSocketAmountReceivedState = (event: string): number => {
const [total, setTotal] = useState(0);
useEffect(() => {
Socket.on(event, () => {
console.log(total);
setTotal(total + 1);
});
return (): void => {
Socket.off(event);
};
});
return total;
}
The logs of run look something like
0
1
1
2
3
3
4
4
4
5
Socket in the example above is implementation around websocket.
So I can deduct that total is not updated fast enough, but what is the best pattern to handle this sort of behaviour ?