Functional Component vs Class Component in React

Author Purushothaman Raju ,Posted on June 06 2020

But First let’s understand what a component is, A component is a reusable piece of UI(user interface) or an element. The logic to show the UI and events related to the UI are all contained within the component making it reusable.

Functional Components
Components that do not have to maintain data or when we would like to only render some UI on the screen then a component can be written as a functional component. Functional components are just Javascript functions which return some JSX, Functional components do not have access to React’s lifecycle methods and state(Though this is possible with the new release using hooks).

See the code example below for functional component

import React from 'react'

const MyApp = (props) =>{
	return (<div>I'm a functional component</div>)
}

export default MyApp

Class Components
If the components need to store any data or contains logic like make API calls, handling multiple DOM events. then it is a good idea to create class components. The class components are based on the OOPS approach. With class components, we will have access to lifecycle methods, state, and More.

See the code example below for a class component

import React from 'react';

class MyApp extends React.Component{
   
    constructor(props){
    	super();
    	this.state={
    		greeting : "Nice"
    	}
    }
	render(){
		return(
             <div>I'm a class component <br/> {this.state.greeting}</div>
			)
	}
}

export default MyApp




The picture below shows the comparison between a functional and a class component

functional component vs class component