Components In React🌐

Humza Sajid
2 min readAug 30, 2021

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.
  • It has complex UI Logic
  • You pass props(properties) to class components and access them with this.props.

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.
  • It accepts properties(props) in function and return HTML(JSX)
  • There is no render method used in functional components.
  • These can be typically defined using arrow functions but can also be created with the regular function keyword.

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.
  2. It has less code(easy to understand)
  3. More developer’s started using because of points #1 &2.

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

--

--

Humza Sajid

Writing easy-to-understand Web-Application Development (JS/TypeScript, React, Node) explanations for myself and others.