intor_react
2019 17 Sep

Introduction to React JS and Components

React is a flexible JavaScript library for building user interfaces and it lets you compose complex UIs from small and isolated pieces of codes which is known as Components. React has the aim to simplify the development of visual interfaces.

Developed by Facebook and was released to the world in 2013. It is already powering the two most common social giant Facebook and Instagram and other companies like Uber etc. Recently Microsoft also adopted React to integrate user chat systems in their office products.

WHY REACT?

React has taken the front-end development world by storm. Below are the key points for that:

  1. Less complex: Before React, Ember.js and Angular 1.x were the main choices for the JavaScript developers. Too many conventions on the code and also two frameworks brought too much to the table. While React decided to only stick with the view layer instead of the full MVC framework. Also moving from Angular 1.x to 2.x was like moving in a different framework. Along with this fact, execution speed that was promised by React, which makes developers to eager to try.

  2. Component-Based: React is component-based. A component is a small piece of code that can be reused multiple numbers of times. It can be stateless or stateful. For example, it can be a header, footer or can be a small element like button on a webpage. We will go into depth later in this article. Below is the example of a normal class-based React component:
    class Homepage extends Component {
      render() {
        return (
          <div>
            <p>Welcome to React Demo </p>
          </div>
        );
      }
    } 

     

  3. JSX: Another interesting fact of using React is `JSX`. JSX stands for JavaScript Extension and is a react extension allowing a developer to write JS which looks like HTML. It also allows writing ES6 and ES7 codes using JSX. When you are writing in JSX then you need to pay attention to a few things. For example. `class` is JS reserved word so instead of `class`, you have to write `className`. For the same `for` becomes `htmlFor`.
    <h1 id={myId} className={ myClass }>Hello, world!</h1>
    

     

  4. Virtual DOM:  Virtual DOM is a tree of nodes that lists elements and their attributes and content as objects and properties. React provide render() method which creates a node tree from the available components and updates it in response to data mutation caused by actions. Whenever data is changing, that particular stateful component re-render and React create a virtual DOM representation for that. Using `diff` algorithm it calculates the actual difference between old and the new virtual DOM and then updates the real DOM with what has changed, which makes React faster than others.

  5. Backed by Facebook: React is backed by Facebook. It benefits a project if it turns out to be successful. It is an open-source project and used in over 2 million projects. 

 

React Component

Before starting, it is a good idea to understand the building blocks of the React and that is Component. It is a typical JavaScript class or can be a JavaScript function that returns an element. Have a look at the below snippet:

class Login extends Component {
    
    render () {
        return (
            <div className='container-custom'>
                React Class based Component
             </div>
        )
    }
}

Above is an example of a class base component is a typical JS class that has render method which is returning <div> element.

const  Login = () => {
    return (
        <div className={'functional_component'}>
            Functional Component
        </div>
    )
}

Above is an example of a functional component which is typical JS function and returning an <div> element.

A functional component is useful for static element rendering which does not contain logic like event handlers. On the other hand, if your element is dynamic and based on logic then the class base component is useful. A class base component also has its state where a component can store its value. A class base component has a life cycle method which is not available for a functional component.

Component Life Cycle

React component’s life cycle is divided into three sections. Initial render, update and unmounting.

Initial Render or Mounting: 

  1.   Initialization: In this phase first thing gets called is component’s constructor where the developer has to define props and states. The following code snippet describes the initialization process.
     constructor(props){
        super(props);
        this.state = {
          loading: false
        }
      }

    Passing props in a constructor and super are required when you have to use props within a constructor. This phase is optional, and this phase is not applicable for a functional component as they don’t have any lifecycle method. 

  2. getDerivedStateFromProps: After successful initialization, this lifecycle method gets invoked. As this is a static method you cannot use this keyword inside this method. Below is the snippet:
     static getDerivedStateFromProps(props, prevState){
        return {
          cachedSomeProp: props.someProp
        }
      }

    Within this method, you will have access to the new props and the previous state as a parameter. If you need to change the component state then you can simply return it as an object or if not then simply return null.

  3. componentDidMount: After successful rendering of the component this lifecycle method gets invoked. This method ensures that the component is successfully rendered on the DOM. Below snippet is the example of this life cycle:
     componentDidMount(){
        this.props.decrement()
     }
    This is the best place to call API or make an asynchronous request.   

Updating

  1. getDerivedStateFromProps: Yes, this lifecycle method called again. After changes on the state, component re-rendered and on every update, this method gets invoked. This is very much useful if you want to change the state based on new props. Have a look on below snippet:
    static getDerivedStateFromProps(props, state){
        if(state.images.length > 0){
          return {}
        }
        return {images: props.attributes}
     }
  2. shouldComponentUpdate: React’s render method gets called on every props and state changes. But if you are worried about wasted renders then this lifecycle method is great things to you. This method usually asks for permission before re-render. This method usually returns boolean true or false. Below is the example snippet:
     shouldComponentUpdate(nextProps, nextState) {
        // only update if no of images change
        return nextState.images.length > this.state.images.length;
      }

  3. render: After changes on state and if shouldComponentUpdate allows then this method gets invoked and re-render the component in the DOM.

  4. getSnapshotBeforeUpdate: This lifecycle method gets invoked after render and before updated to actual DOM. It becomes handy when you need to grab some DOM information just after an update is made. The value of DOM in this method is available is just before DOM is updated.

  5. componentDidUpdate: After new changes are committed to the actual DOM this lifecycle method is gets invoked. This method ensures that your component is updated successfully.
    componentDidUpdate(){
        // do your task here
    }

 

Unmounting

  1. componentWillUnmount: This lifecycle method gets invoked before the component is finally unmounted from the DOM. If you have any component-specific event listener, then it is the best place to remove that. Below is the snippet of this method:
    componentWillUnmount(){
        this.clearListner()
    }

 

Conclusion

In this article, I have covered basic React, component lifecycle, virtual DOM, state and props, etc. To start with React, it is better to use `create-react-app` template as it comes Babel, Webpack, react, react-dom pre-configured. Working with React you will have other advantages like React Native and React VR.
 

Latest Blogs

Blockchain Integration Into Public Digital Good

The Role of Blockchain in Digital Public Goods: Use Cases and Innovations

Digital public goods, such as open-source software, IT models, and standards, are the backbone of our digital infrastructure.

Read More

Role of Open Source and Digital Public Goods

Boost DPG Development: How Open Source Maximizes Efficiency

The emergence of open-source workflow solutions has revolutionized workflow management.

Read More

Digital Public Goods Alliance Strategy 2021–2026

Boosting Digital Infrastructure with Digital Public Goods

The United Nations (UN) defines a roadmap for Digital Public Goods (DPGs) as open-source software, open data, open AI models, open standards, and open content.

Read More

Best Practices for Software Testing

Power of Software Testing: Why Software Teams Use It Effectively

In the modern digital era, where software is used in nearly every aspect of everyday life, the importance of software testing cannot be emphasized.

Read More