Components In React🌐

Objective: Introduction to React Components, finding the differences between functional and class components and which one you should use.

What are the components in React?

React is a JS library for building UI, it’s based on components, let’s understand it with an example let’s suppose component’s like a brick by using multiple bricks we construct a house, In React by using multiple components we design a webpage.

In Software Development repetition is considered a bad practice, React components remove the redundancy of code as components are reusable and can be used anywhere in the user interface.

How many types of components are in React?

There are mainly 2 types of components

1-Class Based Component also known as Stateful component

2-Function Based Component also known as Stateless component

Clas Based Component:

In the beginning, React started with Class-based Components.

example:
import React, { Component } from “react”;
class Welcome extends Component
{
constructor(props){
super(props);
this.state =
{
name: “Humza”;
}
}

render() {
return (
<div>
<h1>Welcome Mr: {this.state.name}</h1>
</div>
);
}
}
export default Welcome;
  • It must have a render() method returning a single HTML tag.

Function-Based Component:

function Welcome(props)
{return
(
<div>
<h1>Welcome Mr: {props.name}</h1>
</div>
)};

export default Welcome;
  • It is a simple javascript function that simply returns an HTML tag.

Which one should I use?😕

You should prefer using Function over Class-based component as:

  1. Functional components are much easier to read and test because they are plain JavaScript functions.

Thanks for reading! I hope this article helps you a bit to understand some basics concepts of React.

Writte easy-to-understand JS , React explanations for myself and others.