reactjssocket.ionext.jsswr

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?


Solution

  • 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.