DEV Community

Cover image for Using WebSockets in React

Using WebSockets in React

Oghenero Adaware on August 19, 2019

Recently I had to consume a WebSocket API in a React application I was working on, So in this article, I will briefly explain how to use it in a Re...
Collapse
 
lai32290 profile image
Lai Xuancheng •

My experience about WebSocket + React is implementing the connection in Redux middleware, including all the received event handler to dispatch Redux action automatically and to it has to do.

And dispatching a action like:
{
type: "SOCKET_XXXXXX"
}

to send event from client to server.

I'll try your solution for next time, it seems really work.

Thanks for share.

Collapse
 
ceikit profile image
ceikit •

This looks good but unfortunately does not work if you try to pass ws to more than one child component.
I find that the first child ends up not receiving any data.
Would you have a solution for this?

Collapse
 
guico33 profile image
guico33 •

What's up with mixing var and let instead of just using const?

Collapse
 
djoleb profile image
Djordje Bajic •

Hello Nero!

Thanks for taking your time to write this post.
Can you consider writing one with websockets + subscription? For example you connect to ws://localhost/something and subscribe to /posts/get?

Collapse
 
ogheneroadaware profile image
Oghenero Adaware •

Alright, will look into it.
Thanks Djordje.

Collapse
 
osamaeshtiaq profile image
osamaeshtiaq •

What npm package to install for this?

Collapse
 
esa profile image
E-sa •

Mine works without any packages.

Collapse
 
umpurevdalai profile image
Purevdalai •

You don't need to install any packages. It works without any packages

Collapse
 
emekalites profile image
Chukwuemeka Ihedoro • • Edited

Nice article bro, helped me a lot. Thanks.

Collapse
 
krishteja18 profile image
krishteja18 •

You can use react-websocket npm package to easily reconnect

Collapse
 
patrickduc profile image
Patrick Duc •

Nice article, thank you.