How real time data update works in React js?

Viewed 5256

Suppose I am consuming an API and getting it's data as:

{USA:12,IND:21,NEP:90,ENG:81}

after sometimes it's data changes to :

{USA:2,IND:1,NEP:0,ENG:1}

and so on...its data is continuously changing, I have created an table in react which shows data for these countries and is updating the table's data every time there is change in data.

Now, I want to know how does table update the data in real time without reloading the page or clicking any button, but by itself.

Is it listening to API every time i.e. making API call continuously, and it fetching data continuously and when there is change in data updates the component or what actually is happening?

This was a question asked to me during interview for which I told that it is continuously calling API and when data changes it updates the table but I'm not sure if this is correct answer or not … or how it actually happens?

If anyone could provide me some article that I can refer to or provide me explanation that would be great.

If anyone needs anymore information please let me know.

2 Answers

For React Applications, there are three ways to get real-time updates.

  • HTTP Polling
  • Server Side Events
  • WebSockets.

There are pros and cons to each approach.

  • HTTP Polling: Pros: Easier to implement Cons: The server is overloaded.
  • Server Side Events: Pros: Easier to implement Suited for publish/subscribe model. Cons: Two-way communication is hard.
  • WebSockets: Serverside support or third-party integration is needed.

Here is more information about different methods to get Real Time Updates.

The question was likely assessing if you knew how React's virtual DOM model works.

When the new data is downloaded (callback from fetch or xmlhttprequest), a setState call (or equivalent hook function) is likely called on a component - passing the json with it.

React will then call the render method of the component (or just invoke the function of the pure component). This render function will reference the state to return a tree of elements. This will in turn cause React to update its virtual DOM, compute a diff with the previous version, and apply those diffs to the actual HTML DOM for the browser. If there's no actual change to the DOM since the last render, then no actual updates are done to the browser DOM. There's probably optimizations and details I'm missing, but that's what I would be looking for in an interview.

Some links that are useful to this.

Virtual DOM and Internals

Reconciliation

Related