Revalidate API data in realtime with SWR

SWR is a library that provides React hooks for data fetching. It’s possible to revalidate your data in realtime by broadcasting events using Liveblocks.

An example usage of this may be a share dialog containing a list of users—when a new user is added to the dialog, we can broadcast an event telling other online users to refresh their user list.

Broadcasting events

A simple SWR hook that fetches a list of users may look similar to this:

To create a function that allows us to update this data in realtime, we can broadcast an event telling other clients to revalidate their data with useBroadcastEvent:

We can then listen for the event with useEventListener, and call the mutate function from SWR to update the data:

Putting it together

If we put everything together, we can display a list of users, broadcasting a revalidate event when a new user is added to the list.

Great, data that revalidates in realtime at the click of a button! You can find an example of this technique being used in the Next.js Starter Kit.