React: Functional Component vs Class Component

Gary Cordero Rosa
2 min readJul 29, 2020

--

As I start my journey through React, I discovered how marvelous it is, its power, and how it can make your code more DRY-er. I stumble onto the react building blocks component. Everything in the React world is made of them, practically the React developers lego.

But what is a component? Components are independent and reusable bits of code. They work in isolation and return a JSX expression which translates to HTML via a render function. They can be called anywhere you need, pretty much like a javascript function.

Now that we know what a component is let’s take a look a the types of components you will find.

Functional Component

function Hello(props){
return <div>Hello, {props.name}</div>
}
//same function using ES6
const Hello = ({name}) => <div>Hello {name}</div>

Class Component

import React from 'react'class Hello extends React.Component {render (){
return <div>Hello, {this.props.name}</div>
}
}

The question is when to use them and why? As a rule of thumb always strive to use functional components as much as you can! They are easier to read, debug, and potentially have better performance than class components since they offer no state or lifecycle methods. So yes, try using class components only when your component needs a state or lifecycle methods.

As an example let’s Modify our Hello class and make it a hello container and make some uses of the state and lifecycle methods, and also make use of our hello functional component to display Welcome Messages

import React from 'react'const Hello = ({name}) => <div>Hello {name}</div>class Hello extends React.Component {
state = {
names:[]
}

componentDidMount(){
fetch("http://localhost:3000/users/names")
.then(resp => resp.json())
.then(names => this.setState({names:names}))
}
render (){
{this.state.names.map(name=><Hello name={name}/>)}
}
}

Now you have a taste of the types of components, their advantages, disadvantages, and use cases. Hope this helps clarify any doubts.

--

--

Gary Cordero Rosa
Gary Cordero Rosa

Written by Gary Cordero Rosa

Flatiron School Software Engineering Student

No responses yet