Introduction to React JS

Introduction to React JS

In computer science, a library is a suite of data and programming code that is used to develop software programs and applications. It is designed to assist both the programmer and the programming language compiler in building and executing software.

Introduction

React JS is a similar JavaScript library developed by Jordan Walke that helps you to create User Interfaces(UI). React was first used in Facebook’s newsfeed in 2011 and then later in Instagram, and WhatsApp by 2012, and released to the public in 2013.

Today, most of the applications are built using Model View Controller(MVC) architecture and in this MVC architecture, React is the 'V' that stands for view.

In ReactJS, everything is a component and each component is responsible for outputting a small, reusable piece of HTML code. It is mostly used to build reusable components and it reduces the re-rendering of the DOM with the help of Virtual DOM.

Usecase

There are many JavaScript frameworks for front-end available in the market but React JS has done is truly exceptional. Let's have a look at some of the key features:

  • JSX - JSX stands for JavaScript XML. It's an XML/HTML-like syntax used by ReactJS. It extends the ECMAScript so that HTML-like code can co-exist with JavaScript react code. This format is rendered to the normal browser Javascript by the pre-processors such as Babel. It is much faster than normal JS as it performs optimizations while translating to regular JS.

  • One-way Data Binding - In this method, the data flows in only one direction i.e the view will not get automatically updated when the data model is changed. This feature gives you better control over your application.

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

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

  • Virtual DOM - Do you remember how Facebook’s UI looked a few years back? You had to reload the entire page for new updates repeatedly. But now it's no longer required and this is the magic of ReactJS.
    Re-render everything on every update? It sounds expensive but it's not. React will make the browser render only if there are any differences and if there are no differences, React will make the browser render nothing. This makes the rendering super fast.

Installation

The best way to have a quick and reliable React boilerplate is to install create-react-app. To do so open the terminal and type:

npm install -g create-react-appcreate-react-app my-app
cd my-app/
npm start

This will automatically open a website in your browser.

Now have a look at the files that were created. It should look like this:

my-app/
  README.md
  node_modules/
  package.json
  .gitignore
  public/
    favicon.ico
    index.html
  src/
    App.css
    App.js
    App.test.js
    index.css
    index.js
    logo.svg

Fundamentals

React has exploded in popularity — and for good reason! Let's study the fundamental building blocks of React and understand things clearly.

  • Component - As I already discussed that ReactJS is all about components. Components make the task of building UIs much easier. React allows you to break your page into independent building blocks that can be created, maintained, manipulated, reused independently, and then merged to construct the entire page.

React JS deals with two types of components:-

Functional Component

  • No state

  • There is no render method used in functional components.

  • Simple JS functions

  • May take props as parameters and return the output to be rendered.

Example:-

import React from 'react';
function App() {
return(
     <div>
          <h1>Hello folks</h1>
     </div>
    ); 
 }

Class Component

Also known as stateful components because they implement logic and state.

  • It must have the render() method returning HTML.

  • More complex and flexible but deprecated.

Example:-

import React, { Component } from 'react';  
import ReactDOM from 'react-dom';
class App extends React.Component 
{
  render() {
     return(
         <div>
            <h1>Hello folks</h1>
          </div>
       ); 
    }
}
ReactDOM.render(
    <App/>, document.getElementById(root)
);
  • Props - When building a react application, the UI is divided into many smaller components. Some of these components are re-used in various parts of the application and to make these components effective props are used. They attribute like entities in components, which can be passed to the children's components. Props are immutable so we cannot modify them inside the child component.

    props.png

Let's see how to pass the data with props from the parent component to the child component:
App.js

import React, { Component } from 'react';  
class App extends React.Component {  
   render() {     
      return (  
          <div>  
            <h1> Welcome to { this.props.name } </h1>    
            <h4>
             { this.props.name }  is one of the best blogging platform.
            </h4>         
          </div>  
      );  
   }  
}  
export default App;

Main.js

import React from 'react';  
import ReactDOM from 'react-dom';  
import App from './App.js';  

ReactDOM.render(
<App name = "Hashnode" />, document.getElementById('app')
);

Output

Default Props- We don't need to always pass props from the parent component. In this case, we need to set up a default prop value to cover up.
Example-
App.js

import React, { Component } from 'react';  
class App extends React.Component {  
   render() {     
      return (  
          <div>  
            <h1> Welcome to { this.props.name } </h1>    
            <h4>
             { this.props.name }  is one of the best blogging platform.
            </h4>         
          </div>  
      );  
   }  
} 
App.defaultProps = {  
   name: "Hashnode"  
}  
export default App;

Main.js

import React from 'react';  
import ReactDOM from 'react-dom';  
import App from './App.js';  

ReactDOM.render(
<App/>, document.getElementById('app')
);

Output

  • State - A state is an updatable object that contains data and also keeps track of changes in the component. States are mutable, which means we can modify the data with the help of the setState() method. It is responsible for making components dynamic. Whenever the state changes the setState() schedules an update to a component associated with that particular state object.
    Example
    App.js

      import React, { Component } from 'react'; 
    
      class App extends React.Component {  
      constructor() {  
       super();        
       this.state = { readMore: false }; 
       this.toggleReadMore = this.toggleReadMore.bind(this);  
      }  
      toggleReadMore()
      {  
        this.setState({readMore: !this.state.readMore});  
      }  
      render() {  
       return (  
        <div>  
         <h1>Welcome to Hashnode!!</h1>  
         {  
           this.state.readMore ? (   
            <div>  
            <h4>
              Hashnode is a free developer blogging platform that allows you 
              to publish articles on your own domain and helps you stay 
              connected with a global developer.
             </h4>
              <button onClick={this.toggleReadMore}> Show Less </button>  
               </div>  
                ) : (  
                <div>  
                 <button onClick={this.toggleReadMore}> Read More </button>  
                 </div>  
                )  
               }  
            </div>  
          )  
       }  
      }  
      export default App;
    

    Main.js

      import React from 'react';  
      import ReactDOM from 'react-dom';  
      import App from './App.js';  
    
      ReactDOM.render(
      <App />, document.getElementById('app')
      );
    

    Output

  • Components Life Cycle - In ReactJS, every component is undergoing lifecycle methods, starting from its initialization. Let's discuss component lifecycle methods in this section-

Initial Phase

This is the phase from where the components start their journey. Here, a component contains the default Props and initial State. This phase occurs only once and consists of the following methods;-
a. getInitialState()
b. getDefaultProps()
The first method will get the initial state information and the second one will get the initial props needed for the component.

Mounting Phase

After the initialization phase, the instance of a component is created and the next step to be taken care of is mounting to the DOM. ReactJS provides the following three methods for this:-
a. componentWillMount()
b. componentDidMount()
c. render()

The first method is called before the render method and if we are setting a state here, it would not re-render the component the second is called immediately after a component gets rendered and placed on the DOM and the last method is defined in every component and responsible for returning a single root HTML node element.

Updating Phase

This phase deals with the updates in the component which happens either due to a change in props or a state change and it repeats again and again. ReactJS provides the following five methods for this:-
a. componentWillRecieveProps()
b. shouldComponentUpdate()
c. componentWillUpdate()
d. render()
e. componentDidUpdate()

4.) Unmounting Phase- Finally, in this phase, the component instance is destroyed and unmounted from the DOM. ReactJS provides only one method for this:-
a. componentWillUnmount() This method is called 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. Hope you have liked the article, do follow me on my social LinkedIn Twitter GitHub.

Resources

Share your queries in the comments section.

1) factweavers.com/blog/introduction-to-reactjs
2) javatpoint.com/reactjs-tutorial
3) mygreatlearning.com/blog/react-js-tutorial
Happy Learning😃😃

Did you find this article valuable?

Support Mrinmoy Porel by becoming a sponsor. Any amount is appreciated!