Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io vs swr for updating real-time content

I am currently building a web app with next.js, which requires real-time updates across devices, for example, if someone joins a group this needs to be instantly shown for all existing members of the group.

At the moment, I'm initially fetching the data for the user when the page loads, and using socket.io to update content when necessary. However, I have just discovered the SWR framework, which automatically updates the content when there is a change in the body of the request.

My question is: am I better off sticking with my current approach, or using the SWR hook? At the moment, quite a lot of data is being fetched on page load, e.g. groups, settings, etc., but would it be more efficient if I used multiple SWR hooks to fetch the groups, settings, etc. separately?

like image 392
isaacholt100 Avatar asked Oct 07 '20 18:10

isaacholt100


People also ask

Is Socket.io real time?

Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server.

Is SWR real time?

SWR is a lightweight library created by Vercel (formerly ZEIT) that allows fetching, caching, or refetching data in realtime using React Hooks.

Is Socket.io better than WebSocket?

Socket.IO is way more than just a layer above WebSockets, it has different semantics (marks messages with name), and does failovers to different protocols, as well has heartbeating mechanism. More to that attaches ID's to clients on server side, and more. So it is not just a wrapper, it is full-featured library.

Does Socket.io use WebSockets?

Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet.


1 Answers

I don't think SWR does what you expect it to do. It helps you send a good ol' HTTP request, cache it and refresh it when you need (e.g. prop change, component mount, after a certain amount of time). The closest thing it does to socket might be "polling on interval".

You can set SWR to refresh the data every 5 seconds for example, but this is not actually a "real-time" connection. If your content requires real-time updates, I would say, stick with socket. If you want to load content from an HTTP server, cache and revalidate it from time to time, SWR is your tool.

like image 123
Gokhan Sari Avatar answered Oct 23 '22 21:10

Gokhan Sari