Real Time Updates in your React Application

What are Real time updates in Web Applications and Why do we need them?

To understand that, we need to know typical web browser interactions. In a typical web browser and server interaction, the browser, a.k.a, the client,  sends an HTTP request to the web server. The server sends back the response in HTML. Once the browser receives the HTML, it renders the HTML as a web page.  The HTML response can include Javascript and CSS to make the web page responsive and interactive. The browser must initiate a data request to receive an update from the server. This basic request-response structure works for most use cases. In fact, the majority of web applications are built using this model.

However, consider a scenario where the server needs to push a notification to the browser. Say there was an update on the server side, and the server wants to push the update to the browser. And this update needs to be displayed without mandating browsers to request the data. 

What if we want our web applications to receive updates from the server without requiring users to refresh the browser? This is the case where we need to implement real-time updates.

In this blog, we will discuss typical use cases, options for implementation with code sample, and when to use it.

What are typical use cases for web applications to have real-time updates? 

Newer generation of web applications shouldn’t be based on simple request/response based ReactJS applications. We need to be able to push the updates instantly – in real time.

Here are typical use cases where receiving real time updates will benefit user experience-  

  • Breaking News and Real time Sports Update: Anywhere there is breaking news or live sports broadcast, where users expect the news to get broadcasted immediately. 
  • Comments and Like counts: Social media platforms where multiple users are commenting and pressing ‘like’ button. Pushing user comments and like count will greatly enhance user experience. 
  • Displaying current logged-in users: Getting up-to-date information about users who are currently logged in or are actively viewing/editing a record would be useful to avoid a record getting worked on by multiple users. You have already seen this functionality in Google Docs and Google Sheets. How cool would it be to implement it in your application? 
  • Displaying Real-time Charts/Data Updates: For displaying rapidly changing charts – such as stock prices. The charts and prices need to get updated immediately on screen without user interactions.
  • Status Notifications: For long ongoing tasks, we need to push updates to the users. For example, we might be writing a food delivery application, and want to update the user status of users order. Whenever food is prepared and ready for pick up, we like users to see the status. This is excellent use case for real time updates.
  • Collaborative Games: Multi player games require real time update.

Methods to implement Real Time Update:

Standard web requests are based on client requests, and the server responds. For web applications wanting to update in real time,  there are three options. 

Option I) HTTP Polling

HTTP Polling is the simplest to implement and requires no server-side support. This isn’t really a solution -but rather a bandaid to get server-side updates. 

In your frontend react application, here is how you can do so. Set up a timer using setInterval. 

If you are using react, here is how you can implement HTTP Polling.

 useEffect(() => {

    const interval = setInterval(() => {
        // Poll the server for new data.
        fetch("https://localhost:4000/data")
        .then(res => res.json())
        .then(
          (result) => {
            setIsLoaded(true);
            setData(result);
          },
         
          (error) => {
            setIsLoaded(true);
            setError(error);
          }
        )


    }, 1000);
    return () => clearInterval(interval);
  }, []);

Option II) Server Side Events (SSE)

Great resource to learn Server Side Event : https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events

  useEffect(() => {
    // Consume 
    const eventSource = new EventSource(serverBaseURL + '/events');
    eventSource.onmessage = e =>  {
      console.log(e); 
      const data = JSON.parse(e.data); 
      setCount(data?.count)}


    
  }, []);

Option III) WebSockets

useEffect( () => {
  // Web Socket
  const ws = new WebSocket(WebSocketURL)
  ws.onopen = () => {
    console.log('connected')
  }

  ws.onmessage = (message) => {
    console.log(message);
  };
  return () => { ws.close();}

}, [])

Conclusion

In this blog, we learned three methods of real-time updates from servers: HTTP Polling, Server Side Events, and WebSockets. We learned how to implement each approach in your frontend application using ReactJS and Backend Application using NodeJS/ExpressJS. 

We discussed the pros and cons of each approach. Finally, we discussed real-life use cases -where each method is best suited for.