Brandon
Brandon

Reputation: 60

Why react JS hooks websocket onmessage reset state?

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:

  1. The difference between put onmessage in useEffect with [] or in just useEffect.
  2. The necessity of useRef in react Hooks websocket (I tried both ways and it looks pretty same on network console.) - I know useRef prevents making websocket every re-render.

I have stuck this issue for all day long. :( Please help me.

Thank you so much!

Upvotes: 0

Views: 855

Answers (1)

Ramil Garipov
Ramil Garipov

Reputation: 473

  1. useEffect without dependencies will be triggered every render. As you need to make subscription only once, it should be with empty decencies [].
  2. In your example, 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

Related Questions