Components In React

Components In React

What are components in React?

Component is a small piece of code that can be reused multiple number of times. React provides us the ability to divide the whole website into numerous small blocks also known as components which works individually on its own scope and follows its own life-cycle. To exemplify it, we can divide a simple website into three components i.e. Header, Body and Footer; after that write separate code for individual components and later render all of these components together in a parent component to make a complete website.

Why to follow Component structure in react?

Dividing the website into components provides us with the ability of component re-usability. What are re-usable components? Using one component many number of times according to the requirement.

Let's take a small example of Header and Footer, no matter what the project is, these components are required every time. So we can create that component once and can use them later in other projects by simply copy-pasting it like we do that from stack overflow.

1. Functional Components:

As you can see, a functional component is a function that returns JSX. Inside a functional component, we are passing props as a parameter to the function.

import React from 'react';

const MyComponent = (props) => {
    return (
        <div>
                <p>My name is {props.name}</p>  
      </div>
    );
};
export default MyComponent;

In this example the code snippet is taking an object as an argument called props( stands for properties) and returns a single JSX.

2:Class Components:

In the class components the JSX will be returned inside the render method.

import React, { Component } from "react";
class ClassComponent extends Component {
    render() {
        return <h1>Hello, world</h1>;
    }
}

The main feature of class-based components that distinguish them from functional components is that they have access to a state which dictates the current behavior and appearance of the component.

What are Props in React:

Data is passed to other components with the help of props. And props work similarly for all components in ReactJS, be it class based or functional. Props in react follows a good hierarchy for the flow of data between the components. Props are always passed down from the parent component to the child component.

Functional Components vs Class Components:

Functional components are easier to read, test, and have less code. Even As per the official documentation from the react.org they suggest developers should use functional components as much as possible. Another reason why functional components are gaining popularity is with the use of React Hooks. Now I don't want to dive into that, that's content for some other blog.