socket.io vs swr for updating real-time content
Asked Answered
I

3

9

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?

Include answered 7/10, 2020 at 18:31 Comment(1)
I'd have a look at Meteor. What you describe (pushing data to the clients when changes happen on the server) is exactly one of its key features. In some ways it does what you think SWR thought should do (and which, optimistically I first thought it did as well).Corrientes
I
18

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.

Interpolation answered 8/10, 2020 at 6:42 Comment(0)
H
0

You can check this feature that SWR brings to tackle real-time communication :

https://swr.vercel.app/docs/subscription#useswrsubscription

Version update: Please update to the latest version (≥ 2.1.0) to use this API.
Harlin answered 4/6 at 9:21 Comment(0)
S
-2

Because useSwr relies on HTTP its much more scalable than websockets, which tie your clients to specific servers for up to hours of time.

Yes, refreshing every 5 seconds with swr is not realtime, but if it serves your purpose using swr will be more dependable when traffic grows.

Starryeyed answered 31/1, 2023 at 21:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.