What is Virtual DOM and few other React Doubts - reactjs

I just started to learn ReactJS. I was used jQuery and Javascript for all my projects previously and got few doubts on ReactJS after gone through tutorials.
Why I need ReactJS, still jQuery is there to update DOM and handlebar, dust is there to handle templating.
There's a concept Virtual DOM,In tutorials I can see it will take a copy of my DOM and updates only needed. Anyone please explain how it's differ normal DOM manipulation.
In React all event handlers are inline, <input onClick={this.eventSample} /> is this recommendable ?
I just started learning,If anyone clears me these doubts with some practical code example. It would be helpful for me to proceed further in React.
Thanks in advance.

With my understanding I'm explaining to make you understand :
Take an example of list times :
If one of these list items updates, then the DOM re-renders the entire list. This is where the DOM’s inefficiency stems from.
Ideally, we’d like to only re-render items that receive updates, leaving the rest of the items as-is.
React’s use of the Virtual DOM helps to reduce this inefficiency.
Normal DOM Manipulation :
Checks through all node’s data at a regular interval to see if there have been any changes.
This is inefficient because it requires traversing every single node recursively.
React's virtual DOM:
Components are responsible for listening to when an update takes place.
Since the data is saved on the state, components can simply listen to events on the state and if there is an update, it can re-render to the UI.
light-weight abstraction of the DOM. You can think of it as a copy of the DOM, that can be updated without affecting the actual DOM.
In fact, a new virtual DOM is created after every re-render.
When updates are supplied to the Virtual DOM, React uses a process called reconciliation — using a “diffing” algorithm that compares/contrasts changes in order to know what updates have taken place.
React then only updates those elements that have changed, leaving alone those that have not.
I hope this helps to shed some light on the advantages of efficiency with React’s use of a virtual DOM.
more at Why is React's concept of Virtual DOM said to be more performant than dirty model checking?
React, it’s so much more than a templating engine.
The JSX is, therefore, broader then template engines.
Hope you know how template engines work. here’s the comparison :
JSX/JS: javascript -> vdom
Template: string -> javascript -> vdom
// File 1 - templates/progress.html
<div class="progress-container">
<div class="progress-bar" data-style="width: $val"></div>
</div>
If you look at the template code, and the component separately, how can you tell where $val comes from?
// File 1 -- progress
const (val) => (
<div class="progress-container">
<div class="progress-bar" style={{width: val}}></div>
</div>
);
In this example, it is perfectly clear where val comes
more at https://stackoverflow.com/questions/32619168/react-engine-vs-other-template-engines
JQuery and React solve two completely different problems.
jQuery interacts with the DOM directly.
The idea is that DOM elements carry around too much unnecessary data, and the virtual DOM abstracts the relevant parts, allowing for faster performance.
In React, you modify the virtual DOM, which it then compares to the existing DOM elements and makes the necessary changes/updates.
Inline Events :
I can understand why you asked this, In HTML DOM you use inline events as “bad practice”.
Here, In React With JSX you pass a function as the event handler, rather than a string.
When using React you should generally not need to call addEventListener to add listeners to a DOM element after it is created.
Instead, just provide a listener when the element is initially rendered.
This is actually a React pro.
Hope I cleared your doubts as much as I can

Related

How is Virtual DOM updated?

Imagine that you've built an application with ReactJs containing a hundred elements. Let's say that in some time, the state of component A changes, and for the sake of simplicity we assume it has only one element and no child component.
My question is: how is Virtual DOM updated in response to the state change?
After a few hours of research, I found two contradictory opinions:
The entire Virtual DOM is torn down; then it is rebuilt from scratch
Only the changed elements are updated in the Virtual DOM.
Unfortunately, official documentation is not clear about this. So, can anybody give the correct answer? (please with supporting reference)
[Edit] : Some parts are imcomplete here, think about reading the comment section !
React update a component when its state or a prop changes. It does a comparison between the previous JSX and the new one and re-render only the differences.
If the parent component has its state or a prop changed, it will be updated.
The child will not be refreshed unless a prop from the parent that is passed to it changes.
Note that the useEffect from the child is triggered first. Knowing that, If you do things that update the state in the child component, then it will be re-rendered everytime (Because the usEffect is triggered everytime if you don't set any dependencies).
Test from Stackblitz - Child Effect is triggered first
Article that made me notice it (I didn't know before this answer :D)
Here is how I understand things in React. To be short, the entire virtual DOM isn't rebuilt from scratch, it's not how JSX comparison works.
I don't have much sources about what I said, but here is the explanation about jsx update from the official documentation. Just that should be enough to eliminate the first point of your list.

how to emulate .transition from D3 in Angular or React

All:
I wonder if I want to do data visualization using React JSX or Angular template to replace D3 DOM manipulation (such as .enter().append() .exit().remove()), how can I implement the animation transition like .transition().duration() in either of them?
For example, I build a line chart, in d3 after I change data set and generate new path, there is animation for those line to transform
Thanks
So, the problem with using D3.js in React is that both want control of the DOM, right?
D3 wants to directly select elements, add elements or remove elements based on the data being used, and add attributes to those elements.
React likes to have everything represented in it's virtual DOM and doesn't like any changes to the actual DOM without it's consent.
After some research, some people try utilizing some of React's different life cycle methods to instigate specific D3 methods at different points in a components life. For example, one approach wants you to return false to ComponentWillUpdate and use functional side-effects to run the D3 code on the actual DOM. While this works for some cases, it's still an improper use of React, and you're losing out on the benefits of passing state to any children components that component may be rendering.
I would suggest researching some of these approaches of how people have tried to tackle the issue, to see the root of the problem.
Also, feel free to try out this library my friends and I made that allows you to plug in your existing D3 code as is, and returns React components, and handles transitions, animations, timers, etc.
http://react-d3-library.github.io/
Always looking for more feedback!

Reactjs - How to make components aware of the current view state?

Tools I'm Using: Reactjs 0.14.7, react-router 2.0.0 (Flux Pattern)
Note: I tagged Redux, just cause I got a hunch(I haven't used it) that what I'm experiencing might be one of the reasons people rave about it.
I understand that react-router already manages which parts of the
component tree are currently in view and renders the components based on the state of the current view tree.
Question:
But what if, based on the components in view, one component needs to know what other components are also in view and behave differently depending on what other components are in view(the view state)? What strategy would you suggest to allow components to be aware of the other components in view?
My Current Solution:
I currently am trying to use the URL to infer this global state, and even parsing it and putting it into a store in order for components to be aware of the view state by listening to changes from that store.
My Issue With This Solution:
In a nutshell managing that view state with a store becomes a highly entangled process with extra actions sprinkled all over the code.
1) Actions must be called for any user event that change the route.
2) Action need to be fired when navigating outside of components(I think its much cleaner to keep action firing in components(feel free to debate that one).
3) You must also consider the back button(currently using react-router onEnterHooks to catch when that happens).
Yet I really like the concept of encapsulating the view state because I can imagine that it creates a nice mental model and also smarter components, but just parsing the current URL and using a utility file to determine the current view state when needed, seems like a much easier/cleaner solution to manage then a store that contains the current view state.
Components should never need to know what other components are being rendered, that's one of the fundamental concepts of React. You're trying to extract the "view state" from your component tree, when your component tree should be determined by your state. If you're already using Flux, you need to keep that information in the store, where it will be made accessible to any component that subscribes.
Flux isn't about making development easier or faster for an individual, it's about enabling practices that make it easier to keep a mental model of what an application is doing. This might come at the expense of some simplicity.
Redux is a refinement of Flux that combines the multiple stores that can be subscribed to individually with a single large state tree, with different parts of the tree created by different "reducers" -- functions that take a state and an action and return a new state. It is exactly "a store that contains the current view state." What you describe is also a pretty good description of the type of development common in hacked together jQuery applications, the type of development React seeks to avoid.
I think the core of your misunderstanding falls into how React component's should be layered. It's a tricky topic, and re-aligning your thought process to accurately understand what is a state vs. prop in your model, is a unique challenge.
But the solution to this problem you are facing is simply to order your components more 'correctly'.
At a high level, each component should only care about the props that are passed to it, and not about anything else whatsoever. However, which props are passed are determined by it's parent Component. As a result, that parent can make those decisions, which then have an end result in the child.
As a simple but practical example;
var Parent = React.createClass({
funcA: function(){
this.setState({propB: 'something new!'});
},
render: function(){
return (
<div>
<ChildA propA={this.state.propA} funcA={this.funcA} />
<ChildB propB={this.state.propB} />
</div>
);
}
});
With this layout of concerns, ChildA is capable of handling user input, passing it to funcA which then impacts ChildB. But all of this happens without the Child components knowing anything about one another whatsoever.

A way to check if html changed in ReactJS

I have a JS code which should do some things (animations etc.) BEFORE ReactJS possibly (or not) will update HTML element. I'm getting the whole template for this HTML element (i.e. part of the page, in particular a widget) for this purpose.
For example, I have a DIV with some content, which may change in time or not. Then I get a new version (i.e. as HTML template) of that DIV through AJAX call, and I want ReactJS first to compare the actual (or virtual) current DOM with the one just retrieved new HTML template for the same DIV in a string as got from AJAX call on success. Only then - when these two are different - it makes sense to do animations first, and only then update the actual DOM in the browser by React JS.
How to do that? Is there a method in React JS that allows me to get e.g. true/false when comparing virtual DOM with its new version as a HTML template got through AJAX (since it does internally this thing anyway - i.e. comparing current and updated DOM in its algorithm)?
EDIT: Hmm after initial thought that ReactJS is way much better than other JS Frameworks in my case (i.e. server functionality is already developed), I found multiple features not flexible enough; further more, I found ReactJS is not smart enough to figure out that only one element at the top of the list is added (ReactJS replaces the whole DOM template for the list, even with keys set for each element!), which suggests it's still not that mature as one could expect.
Besides, all Lifecycle methods with ***Component***Update are not called; only ***Component***Unmount are being called in the case of mentioned list. I can do it in a simpler way by myself, however Relay / Flux + ReactJS architecture is still nice, and I think I'll just abandon Facebook's implementation, and replace it with my own solution, inspired by Relay/Flux+ReactJS.
You might want to look at the following life cycle methods:
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
From the react docs:
componentWillUpdate
Invoked immediately before rendering when new props or state are being received. This method is not called for the initial render.
Use this as an opportunity to perform preparation before an update occurs.
componentDidUpdate
Invoked immediately after the component's updates are flushed to the DOM. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated.

ReactJS Modal Component

How do you create a ReactJS component that reaches multiple levels up the component/DOM hierarchy?
A good example of this is a Modal. I want to trigger and control the modal from a child nested way down in my app, but a Modal requires that the DOM be much higher, most likely all the way up as a child of the document body.
I'm considering a "portal" pattern, as described here: https://github.com/ryanflorence/react-training/blob/gh-pages/lessons/05-wrapping-dom-libs.md#portals
FakeRainBrigand even wraps the pattern up nicely in a mixing in this post: https://stackoverflow.com/a/26789089/586181
This feels like a hack to me. Great if you want to use a non-react library like jquery-ui, but without that need breaking out of react just to render a react component somewhere else in the DOM seems like overkill. Is there a more "React" way of achieving this?
Thanks
I'll leave this best to the react documentation. If you must have buried React elements that need to communicate with other elements outside of their Parent Child or possibly even grandparent than see the below.
For communication between two components that don't have a
parent-child relationship, you can set up your own global event
system. Subscribe to events in componentDidMount(), unsubscribe in
componentWillUnmount(), and call setState() when you receive an event.
https://facebook.github.io/react/tips/communicate-between-components.html
I've written a library to help with this. I avoid the DOM insertion hacks used by Portal strategies out there and instead make use of context based registries to pass along components from a source to a target.
My implementation makes use of the standard React render cycles. The components that you teleport/inject/transport don't cause a double render cycle on the target - everything happens synchronously.
The API is also structured in a manner to discourage the use of magic strings in your code to define the source/target. Instead you are required to explicitly create and decorate components that will be used as the target (Injectable) and the source (Injector). As this sort of thing is generally considered quite magical I think explicit Component representation (requiring direct imports and usage) may help alleviate confusion on where a Component is being injected.
You can completely use my library to bind a ModalComponent to a root level component that you decorate with the Injectable helper. I plan on adding an example of this use case soon. It even supports natural props pass throughs, and all the various component types i.e. stateless/class.
See https://github.com/ctrlplusb/react-injectables for more info.

Resources