Unidirectional Data Flow in React

In frontend development, data (props and states) birth lives (dynamics and interactivity) into our apps. Most often data and how it flows are not observed from a wider perspective. In this article, we will be doing otherwise, talking about how data flows in frontend apps, this is because when you take a step back and have a broader look, there is a pattern.

There are two ways data flow in frontend development, Unidirectionally or Bidirectionally. Other terminologies they are called are one-way binding and two-way binding. One-way binding is used in place of unidirectional data flow, and two-way binding is for bidirectional data flow.

What is Unidirectional Data Flow?

This states that data and how they are updated flows linearly from component to DOM, parents to child, component to views, etc, and vice versa. It enforces one-way out traffic (where one of the parties has to be the source). In this case, there is only one source from which the data is read and updated. (If it still doesn't sound clear, keep reading)

One-way Binding in Action

For example, Parent to child one-way binding: data resides in the parents and are passed to the child. The child cannot mutate the data except the parent's permission is granted to change the data. See the react code for example for a Unidirectional data flow from component to view (or DOM).

function App(){
const [state, setState] = useState('') // a tuple to read (state) and update (setState)
return <div  onClick={()=>setState("hello")}>
    {state}
</div>
}

Even if we replace the div above with a custom component, you will still realize that you cannot change the state except if the setState is called somehow (please kindly remember that the setState is a handler from the parent).

This pattern is popular in the react ecosystem. Redux, Flux, and the Context API use the unidirectional pattern. The state that is read and setter with which the read data can be updated is passed down.

What is bidirectional data change?

With two-way binding, the data is both read and updated all at once. No handler is passed from the parent to the child, and yet the child can change the state that lives in the parent. For most frameworks, the necessary infrastructure to enable two-way binding is given. For example, Angular's ng-model.

Conclusion

It is important to find patterns in frameworks, they would usually help us appreciate the models they are built on and reduce the frustration when we hit the rock. With this article, I hope I have been able to provide a short and quick explanation of the definitions and differences between unidirectional and bidirectional data flow.

Thanks for reading thus far, I am always excited if you ever got here. I am happy this helped. If you find a typo or any other concept you are confused with in this article, please chat me up on Twitter at kelvinsekx.