How real time data update works in React js? - reactjs

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.

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

What's the Best way to Reduce Mobile Data Usage in React and React-Native Apps

Data usage really matters for my targeted users. So, I am looking for an APPROACH that'll help me reduce the number of data fetching during react rerender cycles in React and React-native App.
Let's say I have a page that renders all the Items fetched from an API. Since the API's data can be updated at anytime, I am obliged to re-call the API whenever the user displays this page.
IS THERE ANY WAY FOR ME TO KNOW THAT THE DATA HAS BEEN UPDATED WITHOUT BEING OBIGED TO RECALL THE API?? Because I think that the less HTTP requests I send the less mobile data I consume (Maybe I am wrong... I don't know)
I thought of implementing a solution with Redux and Socket.io :
I wanted to prepare an event called data-updated that will be managed by socket.io and whenever one of the users performs an action that updates the item lits (The API data), the data-updated event will be triggered and all the connected users will be notified. Then in the data-updated event handler I will update the item list state slice in the redux store.
My worry is that since socke.io keeps the connection between users and the server alive during the whole session, Won't this approach consume even more Mobile data than recalling the server at any rendering??
You can proceed with graphql with mutations and its caching mechanism, its pretty cool and if I mention if it is handled efficiently you can run your application in 2g network also with speed. Checkout its usage and advantages over REST you gonna love it. https://graphql.org/
Another way is by using redisCache but personally I've not used it though you can check.
You can use React-query lib for data fetching, updating, caching etc.you can read more about it but read its docs.
https://tanstack.com/query/v4/?from=reactQueryV3&original=https://react-query-v3.tanstack.com/

What's the actual need for RTK Query when fetch API is provided?

Initially the idea of Flux is pretty obvious. The view gets Actions and then emits events based on the Action with which the store is updated. However, when I read through redux-toolkit it seems there are multiple ways of achieving something that should be trivial, namely getting JSON data from an endpoint:
Use the fetch API to get some data from an endpoint
Use RTK query to do the same
Use the React Context API
Using the useEffect() hook
Why are there so many different ways for achieving the simplest task?
Thanks.
This question hides a lot of sub-questions, so I'll try to answer them all as per my experience ( I'm partially a fan of RTK Query ).
To ask for a resource via HTTP from a browser there are not many ways, you have to use xhr or fetch API.
xhr is the old callback-based API, fetch is the modern standard promise-based API.
On top of these APIs many libraries were born to make the process and configuration easier/wider, today you mostly will work directly with fetch or with some gold-standard libraries like axios which is pretty similar to fetch but it has some cool extra features to handle the fetch calls and configuration.
On modern frameworks/libraries like React the problem is not How to retrieve a resource via HTTP, but how to handle the asynchronous call and the side effects that the response creates to the whole application.
So now this opens up to the several options you enlisted.
Basically for very basic fetch calls, you can handle the call inside
a useEffect if it's a GET call that has to retrieve data to show
inside the component that just mounted automatically, or
imperatively start the fetch on a button click for example if it's a
( usually ) POST,PUT, ecc... call.
You can then save the result in a React state, and furthermore pass it throughout your application with a context to let other components access the received response. By the way this leaves you with a lot of other behaviours uncovered, the first one is the loading state during the call, and the error management in case of bad status response or other exceptions. That's surely something you can implement briefly with a useState or better a useReducer hook, by the way, so that's not the real reason why you will feel the need for some async calls manager like RTK Query.
REVALIDATION
What happens if for example you are doing a post call on login of a user that returns the user object with user data, you save that data in a client side state manager ( or React state ) and use that state to display user data in your whole application. During the usage of your application, the user can perform some operations that change his data on DB, so you have to take care everytime he does that, to refetch his data and update his clientside data object, or to return the new user object from each POST/PUT/PATCH etc... call and update the clientside state which is pretty error prone, since you might find yourself having an unsynced clientside/serverside data state if you forget to update the clientside state after each operation, or if there's some issue during these phases. This can often lead to pretty hard to manage and to debug situations.
I'd say this is the First good reason to start using a Fetch manager like RTK Query.
This manager implements a pretty straightforward Tags based revalidation mechanism, that let's you to assign a tag to each Query ( GET ) that you perform, so for example you will make a query when the user logs in that retrieves the user data and you will tag the data with providesTags: 'User'.
Now you can safely perform any number of mutation on your user data on backend, and to each one, clientside, you will tell that as soon as it gets a response, it has to revalidate a certain Tag ( or multiple ones ). For example you might have an editPasswordMutation that changes the user password inside the database, and you will just add a invalidatesTags: 'User', this means that as soon as the user receive a positive from the server confirming that he updated the password, the client knows it has to reexecute the getUserData call, get fresh user data, and save them into the redux global store, so they will be immediately accessible to all the application components that are consuming them.
Totally authomatic.
This whole mechanism would definitely need you to write much more code if you were to implement it yourself.
OPTIMISTIC UPDATES
Most of times you will find yourself not wanting yor UI to wait for server response before showing the effect of a ( for example ) button click. Imagine when you click a thumb up on Facebook, you immediately see it in your UI, and that's not cause they have super fast servers, but because the UI is assuming that the call succedeed as soon as you click the button so it instantly adds a +1 to the likes count of the showed post.
This behaviour is not trivial, since usually when you show data in your application you have and should have a single source of truth. So for example if you are rendering a list of blog posts, you should have retrieved them from your backend database, saved them in your clientside state manager or directly render them as-is. If the first post has, let's assume 10 likes, you will render them based on data.posts[0].likes.count. So that's your source of truth. If you want to add a Like/Dislike button, and you want to implement an optimistic update, you would have to manually alter that source of truth, which is not good at all since it could be shared across multiple components ( in case of a global state ) or to duplicate it, and alter the duplicate, but that's not good either.
It's almost never ( almost ) a good idea to duplicate a source of truth.
RTK Query to the rescue!
With RTK Query Optimistic Update is pretty straightforward to set up, basically EVERY fetch can implement an optimistic update behaviour, since you can use the life-cycle method onQUeryStarted to intercept the immediate start of a call, and then use the utility : updateQueryData to update the data that your mutation is going to invalidate. Extremely SMART.
So in this case you will just have a simple mutation that will add a like to the blog post, that mutation will invalidate the posts data, the single post will be immediately updated in the UI with a +1 like, meanwhile the server will refetch the posts list ( since they were invalidated ) and fresh data in sync will be retrieved, and the user will notice just a pretty smooth experience.
There are many other features, especially involving Cache management, which are a plus, ( even if sometimes they can create some issues ) but I highlight these two main features that alone pushed me to become a user of RTK Query, it might look a bit verbose at start, but it definitely makes things pretty clean and tidy, coherent with the Redux philosophy.
As per docs, the goal of the tool is
It is designed to simplify common cases for loading data in a web application,
eliminating the need to hand-write data fetching & caching logic yourself.
It provides some caching and I personally find it very convenient to have declarative isLoading/error without the need to useState for all of it every time : )
But again, it's only optional: RTK Query is an optional addon included in the Redux Toolkit package.
There are multiple ways to achieve the same goal indeed. There's no gold standard in React world regarding this, for better or worse.

React + SSR: Correct way to handle a component that needs to fetch data first

I currently have a React app that I'd like to use SSR with. All but one component is pretty much static content, making SSR super easy. Everything but the component is rendered just fine and well right now.
My question is how do I go about rendering this component that needs to first get data? Because it's a complex SVG that gets rendered my line of thinking is that having it "update" once data comes in is a bad move, and it would be better for it to just not exist in the absence of data (with an error message).
So here's my plan: I can add a prop to the component to pass in data from a parent rather than keep it as internal state only. So if data is passed, no fetch request in the component is necessary. From there what I can do is take the static bundle output of the app and, when the page is requested, the server will request the proper data just as the component would. Once the data is received, the server can grab the component from the bundle with regex, add the data as a prop, render the component, and stick it back in with the rest of the already rendered static content.
Is this the correct way to do this? It feels a bit complicated, but that might just be how it's done. I'm not sure.
Your intuitions are correct. In current React (17.0), it's quite cumbersome to do SSR with data-fetching inside components.
What needs to be achieved on a conceptual level is that all data dependencies need to be known upfront, ie. before calling ReactDOM's render. This way, one can access the data in a synchronous manner which allows to do one-pass render on a server.
I don't quite follow your idea to "grap the component from the bundle with regex". One way of solving the data dependency problem is to inject the data into React tree from the root component (ie. ReactDOM.renderToString(<App componentStaticData={data} />)) and make the data-dependent component aware of the fact that it can just grab the data from there instead of doing (asynchronous) call. It's important to note that useEffects are not executed on the server.
Another idea to grab all the data dependencies is to do two-pass render. First one is used as a way to collect all resources used, then we await their completion and inject them as static data into send pass.
Third way is to use one of the React frameworks that provide SSR out of the box. You can have a look at (among many others) Next.js or Gatsby. Depending on your setup, this might be easiest or the hardest way to achieve SSR.

How to make redux-form (or Redux in general) work nice with a local database?

It's days or maybe weeks (reading articles, watching videos/talks) that I'm trying to understand how to use Redux and redux-form correctly but it's really hard for me to fully grasp the concept. Maybe my usecase is not well suited for Redux or maybe I'm simply missing something obvious.
What I'm trying to find is a good foundation for a large application. I'm fairly convinced about React, but Redux (and in consequence, redux-form) seems like a good solution for a problem that I'm not having. Still, everybody praises the Redux (or flux) concept, so I want to make sure that I'm not missing something.
Well, the application is heavily database-driven with all data readily available in the browser (it's a offline-first application).
I'm using a in-browser database very similar to NeDB plus a Mongoose-like ODM, but actually the database is a(nother) custom project that I want to open-source once it is stable enough (I do have implemented it already and it works very good so far).
The key points of that database (relevant to this question) are probably that it has all data readily available in the browser and that it supports "live queries" - that means that I can subscribe to database changes and up-to-date query results are pushed directly to any consuming component/handler. Furthermore, the database automatically synchronizes all data with a server in background (two-way), meaning that collections may change contents in any moment.
As UI frontend I'm using Material UI.
The application itself will manage quite a number of different collections and I need to implement a number of forms for the user so that he can edit single documents in certain collections. Depending on the context in the application the user will see a list of all documents in the current collection and alongside a form showing the details of the currently selected document in that list. That form will of course also allow changes of the document. The user will probably only edit (see) one collection/form at a time.
See this quick Mockup for easier understanding:
The list on the left is ridiculously easy to do with React and the live queries described above. It's also "reactive" in that it is always in-sync with the database. However, it doesn't currently use Redux at all. I'm not sure if that's bad or not.
When clicking any item in that list, the details should show up in the form on the right.
I like the redux-form (v6) concept, but I can't figure out how to feed the document data to the form. I know there is initialValues but I could not understand how to use it properly.
I guess I need to push the document data somehow into Redux so that it is reflected in the form. Do I need to "start" a Redux action to push the data into the store?
On the other hand, using classic React state to pass the document (a simple JS object) from the list to my form component seems radically simple to me. At the moment I don't see any benefit from having a global form state in the Redux store. But then, I probably need something else than redux-form (couldn't find anything comparable).
Redux with my database seems also redundant to me since in the end both are global data stores.
I do use Redux already for a handful states that have nothing to do with database contents, like application status indicators and to toggle a global drawer. I'm also using redux-router (and ultimately would like to link the current list selection an unique URI). Yet I'm having a hard time to find a harmonic link between Redux and the database/database-related components.
So, my question in the end is: What's a reasonable way to implement these parts of the application? Redux or not Redux? In either case: how can it implemented?
If all your data is available more or less synchronously locally, Redux might not be that great a fit for your application.
However, if you want to use Redux Form, which provides a lot of form state management out of the box, you will need to use Redux, even if you only use it for the Redux Form reducer.
To initialize your form, you can either pass the values in via an initialValues prop to the decorated form component, or you may also call dispatch(initialize(formName, formValues)) yourself.
you can use the following package I've written:
https://www.npmjs.com/package/redux-offline-wizard
the base idea is to:
1) save redux to browser storage and rehydrate (reload from storage to redux store)
2) add a new branch to redux store to implement an outgoing queue for requests. any async XHR action will add a request to queue. Queue requests will be sent when user is online or comes back online and will be retried if failed because of network conditions

React - How to perform fast re-rendering in a distributed system

So I'm coding in React,
and as far as I understand, every time a user make a local update in a realtime distributed system(such as Firebase, which I'm using) there needs to be a call to update first Firebase, and then if successful, a new object (the old object + the new data we pushed locally) can be sent back from Firebase to the React's Stores and then app will use that object to re-render starting with the top level component of the app.
Yet it feels like my understanding is off because it seems like a complete re-rendering be slow. I think of ajax situations where only the piece that needs to be updated is updated so have smooth updates.
So do I return a whole object and have it re-rendered entirely or just use a success event to go ahead and add that piece of data to the store it belongs to?(which I'm assuming would only cause a re-rending of only the component that is effected by the change?)
In Reactjs, the way to handle this is return the whole object and pass it in to the app the same as for the first response. However, each of your components should implement shouldComponentUpdate to determine whether the new data requires that it update itself. If there's no need, it returns false and that part of the UI does not re-render.
This keeps the app's code simpler since it always does the same thing and you don't have to worry about piecemeal data responses. However the implementations of shouldComponentUpdate can become complex.

Resources