React: Class vs functional components

Mdiouf
2 min readJul 14, 2020
Photo by Markus Spiske on Unsplash

Functional components and class components come as a feature of React. Yet, they have some differences we will look at in this article.

Functional Components

Functional components are normal functions in Javascript. The goal of a functional component is to be predictable. This means they don’t have to do any side-effects. A side effect can mean fetching data from an API.

Here’s a functional component in React

import React from 'react'; function App() { 
return <h1>Hello World</h1>;
}

In general, functional components take props and return something with that prop. This ‘something’ can be a div, a form, a section a title, etc.

import React from 'react';function App(props) { 
return <h1>Hello, {props.name}!</h1>;
}

Class Components

A react class extends from the Component in React. Here’s the same component as before:

import React, {Component} from ‘react’class App extends Component {  constructor(props){    super(props)}  render(){    return (     <h1>Welcome to the App, {this.props.name}!</h1>
)
}}

As you can see, there is a difference between the two components. And that difference is not only in their syntax.

Class components are also called ‘smart’ components. They can hold a state and component lifecycles.

Functional components didn’t have access to those parameters…until recently. That’s why we call them ‘dumb’ or ‘presentational’ components. They don’t do anything other than returning a JSX element with props.

React Hooks: a way to make functional components ‘smart’

React hooks appeared to give access to the state and lifecycle methods from a functional component.

This now makes the two types of components almost identical. For more understanding about React Hooks, look at my article here.

Which one should you use?

Before the hooks, the rule was:

  • Use class components if your component uses the state
  • Use functional components if you don’t use the state or any lifecycle method.

Right now, this difference doesn’t apply anymore. Which makes things less clear on when to use one or the other.

As a rule of thumb, I prefer to use functional components. This is because of many reasons:

  • They are less verbose: you write fewer lines of code
  • They are more simple
  • Less confusion because of the this keyword
  • They are easier to test
  • You can have access to lifecycle methods with useEffect
  • You can have access to the state with useState

--

--

Mdiouf

I am a full-stack developer with a passion for technology and learning new things. Founder of JavaScriptLearned.