While building BuilderX, a design tool to bring Design & Code at a common place, I came across different design patterns and this post is a humble effort to share my learnings, as the journey continues
React is more or less based on functional programming concepts and that’s the perception with which the proclaimed leaders of React have embraced concepts like immutability at its core.
React, and its community, is generous with its capacity to provide alternative patterns and that’s the beauty of it. For example, MobX is based on the concepts of OOPs, and thus allows mutability and nesting of states. Exploring Object-Oriented Concepts with React!
We have decades’ worth of work in Object Oriented Patterns and thousands of apps built using this paradigm. I am not going to compare Functional against OOPs concepts since the goal of this article is to explore the idea of adopting such patterns in React!
In OOPs, we have patterns like
MVC stands for Model-View-Controller and here is the formal definition from Wikipedia:
Model–view–controller is an architectural pattern commonly used for developing user interfaces that divides an application into three interconnected parts. This is done to separate internal representations of information from the ways information is presented to and accepted from the user. The MVC design pattern decouples these major components allowing for efficient code reuse and parallel development.
With a view to brevity in this experiment, I am going to build a simple app which has the following :
A simple app which has
In this particular experiment, the model can be named as UserInputModel. The View is the HTML render which is seen on the screen and the Controller handles user actions.
In React, View and Controller usually reside in the same place. Let’s call it UserInputViewController (or we can even call it UserInputComponent).
Later it can be used like
In the experiment above, if the model is updated from a source other than the controller, this component wouldn’t update, and that’s the reason why MVC design pattern recommends that the View should listen to the changes from the Model. How can we do it? Let’s see!
Let’s improve the Model to emit changes:
So, this is how MVC can be implemented in React! This is a quick look at how React can incorporate an array of design patterns, and I hope to cover other patterns in my next blog.
See you then!