Introduction to React

What is React?

ReactJs is an open source javascript library, developed by Facebook’s Jordan Walke in order to build user interfaces both in web and mobile systems. React was first used in the Facebook’s newsfeed in 2011 and then later in Instagram by 2012, and released to public in 2013.

React is the best fit for applications which are prone to dynamic and fast changes in data in their UI.In such scenarios, React can render the changing parts of the UI without re-rendering the entire page as a whole and deliver a much faster user experience.

Why ReactJs?

With the introduction of NodeJs earlier in the last decade, the interest in Javascript world has tremendously shot up. And afterwards, the world is witnessing a plethora of Javascript libraries and frameworks both in frontend and backend. So in this multitude of Javascript frameworks and libraries, what makes React stand out?. Or why should we chose ReactJs?. Let us have a brief look in to what ReactJs has done to the front end world that made it so popular and one of the most sought out options in the world of UI development.

Traditional Frameworks

In the traditional framework scenario, the UI rendering was based on the Document Object Model (DOM). This translates to, whatever we see, was represented as an object and that was rendered in the browser. This approach is fine for small to medium scale applications, but in large applications, especially in applications which had constantly changing data, traditional frameworks rendered poor performance both in terms of speed also in terms of state management. In these architectures, for every change in the data, the DOM was required to re-render causing the entire UI to re-render and thus introducing sluggishness and also erroneous mixing up of states in worst cases. Not so long ago, before introducing React to Facebook’s main web application, it was noted that the Facebook chat was a mess with a lot of bugs. This was one of the main factors which made the engineers at Facebook to try something different to resolve these issues.

React vs Traditional Frameworks

Now coming to React, and what it did to address the above issues, was the introduction of Virtual DOM. In short, what Virtual DOM does is to create a copy of the previous DOM and then take a diff with the current one, which results in getting the changes. Now only these changes are successfully rendered in the UI and hence only the changes are rendered here rather than the entire DOM, it becomes extremely faster. React achieves this through a unidirectional data flow, which makes the state management precise and free of ambiguity, hence solving the second issue we saw earlier in the traditional frameworks.

Popularity

These two changes brought in by React, escalated real fast and high within the front end developer community and had seen several unforeseen repercussions like Google scrapping out AngularJs to rebuild Angular which had to incorporate the changes inspired from React.
Since it is from the Facebook family, it enjoys  the dedicated attention from the Facebook team and also huge developer support in the open source community

Thus even though ReactJs is not a well established MVC framework and only a library which takes care of the view part in the MVC, it has created its own space in the developer world and is one of the leading choices when it comes to build user interfaces.

Distinguishing Features

Following are some of the very distinguishing features of ReactJs which makes it popular and well as unique among the competition:

1. Virtual DOM

I have mentioned the concept of virtual DOM briefly in one of the previous sections, and in this section let us see it in detail. The regular DOM is actually an object containing all the HTML tags as nodes. It also has the ability to do the updates to itself whenever there is a change. Now the issue with the regular DOM is that it is not designed in such a way that only the changes made to it are updated. In regular DOM, the updation happens to the entire tree of nodes and thus wasting a lot of resources and time.
Now let us see exactly how the Virtual DOM is actually making everything fast.

1. React will make a copy of the DOM object whenever it is rendered in to the browser. This copy is called as Virtual DOM

ReactJs

2. Whenever there is a change to the DOM, by user interaction or by any other means, React will generate the copy of the Virtual DOM

3. Now the copy of the real DOM representation and the previous DOM representation are compared and the difference is calculated

ReactJs

 4.  If there are any differences, React will make the browser render only the differences. And if there are no differences, React will make browser render nothing. By this approach,only minimal updation of the browser/real DOM is needed, and that too using minimal resources. This also makes the rendering super fast.

2. Unidirectional data flow

React is designed in such a way that it gets a better control over the state or data flow. For this to happen it has chosen to distance itself from the two way data binding methodology which is heavily used by MVCs. Rather React chooses to go with the one-way data binding. In this method, the data flows in only one direction, that is in simpler terms, the view will not get automatically updated when the data model is changed. Here React will not take care of the updation/changes in UI when the data is changed, rather we need to write separate code to do that each time. This ensures an additional control over state compared to two way data bindings. Making this data control one step closer will help in making the components more independent and loosely coupled.

3. Learning curve

A learning curve is real low for React and it comes from the fact that it is not a framework The later has a lot of domain specific things to know before getting started. React is only a library and that too written in plain javascript which makes the implementation also easier to understand. All that is required from the side of a developer to get started is a basic knowledge on Javascript, HTML and CSS.

4. JSX

JSX stands for Javascript XML and is the syntax used by React, which enables the mixing of Javascript with HTML.This makes HTML to be embedded in the React Javascript code. This format is rendered to the normal browser Javascript by the pre-processors such as Babel. This syntax can significantly boost the performance of rendering and also has good readability when it comes to component based architecture

5. Testing friendly

In React, every element will be treated as a components (we will be seeing React components in detail soon). This means that a page with multiple elements can be broken down to simple components and these components are ideally to be independent from each other. So writing test cases to these components are much easier, since each component lives in isolation with respect to other components and also state.

6. Performance and light weighted

Owing to the Virtual DOM, excellent state management and the component based architecture the performance of  React surpasses or is in par with many of its competitors.

Also the light weightedness of React due to the fact that it is not a framework and only a small javascript library also adds to the performance factor.

7. Native Support

React also have a native version called React Native which offers the best of React world to the mobile app development platforms. React Native supports the simultaneous building of apps in both Android and iOS platforms.

Fundamentals of React

In the previous sections, we saw that why React is so popular and also the compelling feature sets offered by the React ecosystem. In this section, let us explore the fundamental building blocks of React and dive into a little bit of React code to understand things clearly.

1. Components

React follows a component based architecture. This means that, unlike the traditional applications where the entire page displayed is a single element, here each page is broken down into different small units, which are designed to be maximum independent from each other. By this way, bigger applications can be broken down into several smaller individual components. This ensures high reusability,better organisation and easy readability of the application code.

A general implementation practice for components in the React world is to make a component, the root and then make other components in the page its children, such that when the DOM is built, we can have the concept of parent and children nodes. And the unidirectional data flow always happens from parent to children. So suppose the data for a node changes, it can re-render itself and its children without affecting its parent or the hierarchy of nodes above it. This way the component keeps the individuality/isolation associated with it.

Now let us see how a simple component would look like in React:

import React from 'react';
import ReactDOM from 'react-dom';
 
class HelloWorld extends React.Component{
    render(){
        return(       
              <div>           
                <span>Hello World Component</span>
              </div>
        );
    }
}
ReactDOM.render(
    <HelloWorld/>, document.getElementById(root)
);

In the above, you can see that we have created a component named HelloWorld. Each component would have a single render function, where we are returning the HTML for rendering. Since it is the HTML which is going to get rendered, it should also be enclosed in valid HTML tags. Now if you see the render method, it has the component mounted to the id “root” of the page.

2. Props

Props or properties, is designed for inter-component communication. They are simply, attribute like entities in components, which can be passed on to the children components. Also, in some cases, when the component needs to have data, even when the parent component is not passing the data to children components, in such cases we can use default set of props for the children components, if necessary. Props/properties are strictly recommended to be immutable and is only to be managed by the component owner. This is to aid React with its fundamental principle of unidirectional data flow.

Now comes the case where, a component is going to receive data, not from its parent component, but by other means, for example a trigger by the user or so. In this case, we are going to use “state”.

3. State

Since props are not to be changed, there should be some way to handle the changing data in React, and here is where “State” comes up. The “state” helps in keeping track of the data of a component, in between it rendering activities. When the state changes, the components associated with that particular state object is re-rendered. The wiring of the change in state and the component re-rendering is taken care of the React.

There are stateful components and stateless components. The earlier ones uses state whereas the later wont (which is the recommended practice)

4. Component Lifecycle

We have seen, what a component is and also its associated state and props concepts. Another major topic of interest considering the components in React, is their lifecycle. Each component is undergoing a lifecycle in React, starting from its initialisation. Let us have a short look at the component lifecycle in this section.

There are four phases to the component lifecycle as mentioned below:

1. Initialisation

In the initialization phase, the data and the other properties associated with the component which should be there in order for the component to operate should be passed on. React has made available 2 such methods for this namely the

       a. getInitialState

       b. getDefaultProps

As the name indicates, the first one will get the initial state information and the later would get the initial props needed for the component.

2. Mounting

After the initialisation phase, the component would be ready with the data supplied by the state or props and the next thing to be taken care of its mounting to the DOM. React provides 2 methods for this as listed below:

       a. componentWillMount
This is called before the render method and if we are setting a state here, it would not re-render the component.

       b. componentDidMount

This is primarily for DOM manipulation after the component is rendered and is called after the render method.

3. Updation

Now this phase, deals with the changes/updates in the component which can either be caused due to the props or due to the changes in the state. A brief of the methods used in the updation process can be found in the diagram given below:

ReactJs

4. Unmounting

Finally in the unmounting phase, the component is removed from the DOM and hence in some cases there should be some cleaning up to be done. In these cases we are provided with the method called “componentWillUnmount” and is executed just before the component gets removed from the DOM

Conclusion

In this blog, I have introduced you to ReactJs and the main concepts and philosophies behind it. This is more like a theoretical approach to keep in mind while designing a React app. In the next blog to this series,  we will create a login application with React and familiarize ourselves with most of the concepts mentioned in this blog.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>