Table of contents
1.
Introduction
2.
What is a Component?
3.
Why use components?
4.
Type of Component
4.1.
Class Components
4.1.1.
Creating a class component:
4.2.
Functional Components
4.2.1.
Creating a function component:
5.
What are lifeCycle Methods?
5.1.
componentDidMount()
5.2.
componentDidUpdate()
5.3.
componentWillUnmount()
6.
Frequently Asked Questions
7.
Key-Takeaways
Last Updated: Mar 27, 2024

What Are React Components?

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Creating complete websites using HTML alone can be repetitive and challenging. The React library adds functionality and reusability to websites through JavaScript. It is possible to break up the user interface into separate components that can be reused and handled independently with React components. Using React components, optional inputs are converted into React elements rendered on screen. Let's see how we can do that.

What is a Component?

A typical React app will have many components, and they make up the building blocks of the app. Components are classes or functions that accept properties(props), return React elements, and describe how sections of the UI (User Interface) should look and behave.

Why use components?

If you are a developer, you are probably going to make websites where most of the information is going to be necessary, like navigation bars, footers, menus, etc.; therefore, writing the same code again and again will be a lot draining, so writing dry code (Don't Repeat Yourself) will be the best way to save time.

Before jumping into more details, let's be clear about what are props and state:

Props: Props (Properties) are data types passed between React components. It is a unidirectional data flow between components in React (from parent to child).

State: Components in React can also manage and create their data through a built-in object called state. The difference between components and props is that components cannot pass state data but create and manage it internally.

Type of Component

Class Components

A class container/stateful component is a regular ES6 class that extends the component class from the React library. Unlike stateless components, stateful members can control how the state changes and how the component's logic is implemented. Besides that, they can access all the phases of a React lifecycle method.

Class components were the only option before React Hooks to create a dynamic and reusable component since they provided access to all React lifecycle methods and functionality.

Creating a class component:

First, create a file inside a .js file inside the src folder.

import React from 'react';
export default class Coding extends React.Component {
	render() {
		return <h2> Hey, calling by class </h2>;
	}
}
You can also try this code with Online Javascript Compiler
Run Code

 

After that, call that file in App.js.

import React from 'react';
import './App.css';
import Coding from './MyComponents/coding';

function App() {
	return ( 
	    <div> 
	    <Coding title = "First Component" /> 
	    </div>
    );
}
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Functional Components

Functional components are just JavaScript functions. The components used to be called stateless or presentational components before hooks were introduced to React because they only displayed data. To access more React features such as state and React lifecycle methods, up until now, you had to use the class component.

Hooks: They offer you the ability to implement state, and other React features and, most importantly, can be used to construct your entire UI with functional components.

Since this is a function rather than a class, you do not require a constructor or render function. UseState allows you to add states to functional components using only features to class components with hooks.

Creating a function component:

First, create a file inside a .js file inside the src folder.

import './App.css';
import Coding from './My Components/coding';

function App() {
	return ( 
	    <Coding title = "First Component" /> 
	);
}
export default App;
You can also try this code with Online Javascript Compiler
Run Code

 

After that, call that file in App.js.

import './App.css';
import Coding from './My Components/coding';

function App() {
	return ( 
	    <Coding title = "First Component" />
	);
}
export default App;
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

What are lifeCycle Methods?

DOM events can be detected at predetermined Lifecycle times and handled by React Lifecycle methods. Remember that React's primary purpose is to modify the DOM (Document Object Model) accordingly to display what components you want on the screen. The DOM nodes are added, updated, and removed by React. Every stage in React's lifecycle corresponds to a distinct lifecycle method.

  • Mounting: Birth of your component
  • Update: Growth of your component
  • Unmount: Death of your component

componentDidMount()

The Document Object Model (DOM) is mounted by mounting all the children elements and components. Invoking this method will trigger a new render, and it will provide us with access to UI and children's references. Calling the setState() method from the componentDidMount() method is the most suitable way to change the application's state. Updates are also rendered through this method.

import React from 'react';
export default class coding extends React.Component {
	constructor() {
		super();
		this.state = {
			data: null
		}
		Console.warn("constructor called first")
	}
	componentDidMount() { //it is called the data is ready
		this.setState({
			data: "If it is update"
		});
		Console.Warn("component called third")
	}
	render() {
		console.warn("render called seconds")
		return <h2 > hey, Calling by class < /h2>;
	}
}
You can also try this code with Online Javascript Compiler
Run Code

 

componentDidUpdate()

This method is called immediately after the DOM's updating is complete, along with componentDidMount(). A less common life cycle method called getSnapshotBeforeUpdate returns a snapshot value (this value is returned by componentDidUpdate ). In general, you use this method to modify the DOM in response to an update, such as an autosaving feature.

import React from 'react';

export default class coding extends React.Component {
    constructor() {
        super();
        this.state = {
            current: null
        }
    }
    componentDidUpdate() {

        Console.Warn("componentDidUpdate")
    }
    render() {
        return (
            <div>
                <h2>componentDidUpdate</h2>;
                <button onClick={() => { this.setState({ current: "true" }) }}>Start</button>
            </div>
        );
    }
}
You can also try this code with Online Javascript Compiler
Run Code

 

componentWillUnmount()

Components unmount, or destruction invokes the componentwillunmount() method. Cleaning up the component involves this method. Removes items that are no longer needed, such as network requests, event listeners, etc.

Three phases are involved: mounting the nodes, updating the nodes (if they've been updated), and unmounting them. This is called React's lifecycle method.

import React from 'react';

export default class check extends React.Component {

    componentWillUnmount() {
        alert("Checking")
    }
    render() {
        return (
            <div>
               <ul>
                   <li>React</li>
                   <li>Angular</li>
                   <li>Vue.js</li>
               </ul>
            </div>
        );
    }
}
You can also try this code with Online Javascript Compiler
Run Code

Frequently Asked Questions

Q1. What is the difference between functional and class components?

Ans. With both styles - functional and class - there are advantages and disadvantages. In general, functional components are preferred in most cases. It is easier to develop, test, and understand functional components. As a result, class components can be confusing as there are multiple uses of "this." Consequently, for ReactJS app developers, functional components can be somewhat annoying.  

 

Q2. What is the use of render() in React?

Ans. This function returns the HTML, which will be displayed in the element. It is required for each component to have a render() function.  If you need to render more than one element, all components must be inside one parent tag like <div>, <form>.

 

Q3. What is a state in React?

Ans. In React, a state object stores information about a component. As a component's state changes, it must be re-rendered every time it changes. As a result of this user action or an event generated by the system, the state may vary. These changes determine what will happen to the component.

 

Q4. What is the purpose of using the super constructor with props argument?

Ans. This reference can only be used in child class constructors after super() is called. The same applies to ES6 subclass constructors. It's important to pass props parameter to super() call so that your child constructors can access this. 

 

Q5. What are the advantages of using React Hooks?

Ans. In general, hooks enable computations common to a set of components to be extracted and reused without imposing additional burdens on higher-order components. Hooks can easily change our functional components without converting them into class components. Because hooks allow you to use React without classes, they do not work inside classes.  

These methods let us completely avoid calling lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. To accomplish this, we will use the built-in hooks like useEffect.

Key-Takeaways

Thanks for reading this blog. I hope you enjoyed it. In this, we compared how React composes components using the two approaches. The Component class extends React's component library to create a stateful component. It implements ES6 with the help of the React component library. Unlike functional components with hooks, presentational components can be built only from stateful components. In addition, we explained how to choose between the two components and how to implement them in a react project.

Why stop here? Boost your knowledge about ReactJs by reading other blogs on it. 

Live masterclass