Jwan622 Jwan622 - 16 days ago 7
React JSX Question

Is React's data-binding really one way? It seems like it is two way

This is from a couple React tutorials that I'm currently reading:


the State drives what the guys at Facebook call one-way reactive data
flow, meaning that our UI will react to every change of state.


and


Typically UI’s have lots of state which makes managing state
difficult. By re-rendering the virtual DOM every time any state change
occurs, React makes it easier to think about what state your
application is in. The process looks something like this, Signal
to notify our app some data has changed→ Re-render virtual DOM ->
Diff previous virtual DOM with new virtual DOM -> Only update real DOM
with necessary changes.


The first quote seems to suggest that the data flow goes from React to the UI. But the second quote seems to suggest that it goes from the DOM to React which then re-renders the virtual DOM and the diff process than repaints the real DOM. This sounds a lot like Angular's two-way data binding.

Is this true? What am I missing? Is one-way reactive data flow just another name for Angular's two-way data binding?

Answer

I think it's necessary to make a distinction between React and Flux, both of which implement a uni-directional data flow. I'll only touch on React here.

In Angular a change to the DOM will directly mutate the value of bound scope variables in your controller thanks to angular's two-way data binding and the digest loop. It is two way because, of course, any change in your controller is also directly reflected in the view attached to it.

Think of Angular as Controller <--> View

In React a component always renders its DOM based on its props and internal state. A React component can listen to event being fired in the DOM it rendered, which might sound a bit like two-way data flow on the face of it but there is an important difference: An event fired on the DOM does not directly update the internal state of the component. The component must listen to the event and then explicitly update the component with the new state. This change of state then triggers the DOM to be re-rendered (if it needs to). In this way the components props and state are the single source of truth and always drive the DOM output. Of course changes in the DOM can affect the component but it is done in an indirect manner.

Think of React as Component State --> DOM --> New Component State --> New DOM