The ability to update content in real-time can make the difference between a good and bad user experience. Imagine having to reload your browser to se

How To A Build Real-time React App With Server-Sent Events

submited by
Style Pass
2021-09-03 05:30:07

The ability to update content in real-time can make the difference between a good and bad user experience. Imagine having to reload your browser to see if the person you are chatting with has sent a new message.

With long-polling an HTTP request is made to the server at a predefined interval. In server-side events, the browser’s event source API is used to open a channel of communication between the client and the server for updates to flow from the server to the client. The web socket protocol opens a two-way communication channel between the client and the server to allow updates to move in both ways.

The purpose of this article is to teach you how to leverage the browser EventSource API to build a real-time React application, its limitation and use cases. On that basis, this article shall be divided into three parts.

Server-sent events are updates sent in the form of DOM events from the server to the browser. The browser uses the EventSource interface to establish a connection capable of receiving these types of event from the server. An event handler can then registered to handle the incoming event. These can be achieved in a couple of lines of code, depending on is to be done with the received event. Let's say we want to log the event on the console, it can be done in two lines of code:

Leave a Comment