React.js has been popular among web app developers recently and a lot of websites has adopted the library because of the perks it provides. This post is not about pros and cons of the React.js library, although you can find a myriad of articles and posts on the web comparing React.js with other front-end frameworks.

In layman’s terms, React.js is a JavaScript library which handles the view component of the MVC architecture. React.js is used to manipulate the DOM of a webpage in an efficient manner to render a web application.

Now if we look at the file structure within the hello world app, there are three important files. Those are public/index.html, src/index.js, and src/App.js files. In the index.html file, you can see that there is a div with the id root and in the index.js file there's the below code segment.

ReactDOM.render(, document.getElementById(‘root’));

This is the starting point of our app. Basically, React will inject out app component into the div with the root id. Now you might be wondering, what is the app component? If you look at the App.js file, you will be able to see the app component. In React, it is the convention to name JavaScript files with the same name as the component.

React Component

Above is the simplest component we can write in React. We can create a JavaScript class for our component and extend it from the Component class from the React library (Note the import statement). After that, we need to implement the render() method. Prior to React 16, it was a must to return a single element from render method. But with React 16, we can return an array of elements. Now, if we execute an npm start command within the hello world directory, we can see that 'Hello World' is rendered in http://localhost:3000

React JSX (Syntactic Sugar for JS)

In the render method of the component, we can almost use the HTML syntax. But in reality, this is actually JavaScript, specifically known as JSX. JSX is a template language which has a similar structure to HTML with the full power of JavaScript. Hence, you can evaluate any JavaScript statement within the render method.

Note the new import statement for the Alice component. Without that, our app will break since React is unable to find the component which corresponds to the Alice tag.

Next, let’s see how we can manipulate the state of our components. For each React component, there is a state and by manipulating the state object we can change the behavior of our component. This state object is specific to the component.

As shown above, we can declare the state object within the constructor (note that it is a must to call super()within the constructor of a React component). This state object contains the greetings property with the value “Hello World!” In the render method, we have used this property as {this.state.greeting}, and this is the usual way of evaluating JavaScript expressions within JSX. You can add as many properties as you want to the state object. Now let’s see how we can pass data from the App component into its child component, Alice.

If you look at the constructor of the Alice component, there is a method argument named props. This object contains all the data passed from the parent component (input from parent component to the child component). I have initialized the state of the Alice component using the newMsgproperty passed from the App component. If you have used another string as the key instead of newMsg, you can access it with the following pattern: props.newMsg.

Now the app should be rendered as shown below (Figure 2).

The below table summarizes the basic differences between state andpropsobjects of a component.

Another very important thing to note is that whenever we want to modify the state object, we do it through the this.setState() method, as shown below.

In the constructor, I have added a timeout function which modifies the greeting message to “Hello World Update!” after 10 seconds. DO NOT use this.state.greeting = “Hello World Updated!”to update the state as it would not work since React uses an event-driven approach rather than using dirty checking to maintain the state of React components.

React Component Lifecycle

React provides highly valuable lifecycle hooks (method) for each state of the component as listed below. These methods can be classified into 3 categories: mounting, updating, and unmounting.

Mounting hooks are fired when the React component is initially being rendered in the browser page. The below methods are fired in the specified order.

constructor() - Invoked when creating the React component for the first time.

componentWillMount()- Invoked before adding the component to the actual DOM of the web page.

render() - Invoked when adding the component to the actual DOM.

componentDidMount() - Invoked after adding the component to the actual DOM.

Updating methods are invoked when the component is re-rendered on the web page. This happens due to changes in state/props objects. The elow methods are invoked in the specified order.

componentWillReceiveProps(newProps) - This method is invoked when new props are received from the parent component. Note that this method will not be invoked at the initial time when the component is created even though parent component passes props. The initial time should be handled within the constructor.

shouldComponentUpdate(nextProps, nextState) - This method is invoked before the component is re-rendered. It is a must to return a boolean from this method. If true is returned, the component will be re-rendered and the component will not be re-rendered if false is returned.

componentWillUpdate() - This method is invoked before the component is re-rendered in the actual DOM.

render() - Invoked when the component is re-rendered in the actual DOM.

componentDidUpdate() - Invoked after the modified component is re-rendered on the actual DOM.

As for the unmounting, there is one hook named componentWillUnmount(). This method is invoked immediately before the component is removed from the actual DOM. Apart from that, starting with React 16, there is another lifecycle hook named componentDidCatch() which will be invoked when there is an exception during any of the lifecycle hooks of the component. This method can be used to gracefully show an error message when a React component fails to function as expected. For more information on the component lifecycle events, take a look at the awesome React documentation.

Virtual DOM vs Real DOM

When applying the changes of a React component to the actual web page, React uses a virtual DOM to calculate the changes and then apply only the modified bits into the real DOM. Since React completely builds the virtual DOM, you might be wondering, why not build the actual DOM instead? Re-building the actual DOM is quite expensive since the browser needs to re-calculate all the CSS properties, re-draw the canvas, and fire all the event listeners unnecessarily. Hence, building the virtual DOM and applying only the difference to the actual DOM is quite efficient and this process is known as reconciliation. React implements a heuristic based algorithm to calculate the difference between the virtual and actual DOMs, which has a time complexity of O(n).

As an example, when rendering a component, initially both DOMs are empty (Figure 3).

First, the virtual DOM is populated with the content (Figure 4).

Next, the real DOM is populated with the content and the virtual DOM is cleared (Figure 5).

After that, for any change, the complete virtual DOM is generated with the newly modified content (Figure 6).

Next, the difference is calculated and only the modified section is updated in the real DOM and the virtual DOM will be cleared (Figure 7).

This sums up for the basic introduction to the React.js and it is time for you to get your hands dirty and start building your first React app to get some first-hand experience. In the next blog post let’s see how we can craft an elegant data flow between React components using Flux. Until then, happy coding!