Reputation: 60
I am struggling with using Web socket in ReactJS.
I have followed this solution: https://stackoverflow.com/a/60161181/12962511
This solution works pretty good!
However, I wonder why onmessage is in useEffect.
I tried onmessage in the useEffect with [] which is componentDidMount. This results reset my states but not starting the function from the beginning because useEffect with [] did not get triggered in this case.
So my question is:
I have stuck this issue for all day long. :( Please help me.
Thank you so much!
Upvotes: 0
Views: 855
Reputation: 473
useEffect
without dependencies will be triggered every render. As you need to make subscription only once, it should be with empty decencies []
.useRef
is used only to pause listening to messages via websocket. If you don't need this logic, you able to not use it.Upvotes: 1