Category Archives: React

React – Functional Components VS Class Components

1. Syntax

A functional component is a plain JavaScript function that returns JSX, where the class component is a JavaScript class that extends React.Component which has a render method.

2. Extend component

Whenever a class component is created, it is necessary to extend the component, however, if a functional component is created, it is not necessary to extend the component. With functional components, we can use props directly.

Functional component example

// Using ES6 arrow functionimport React from "react"; const FunctionalComponent = () => { return <h1>Elephant Solutions</h1>;};

Class component example

// Using destructuringimport React, { Component } from "react";​class ClassComponent extends Component { render() {   return <h1>Elephant Solutions</h1>; }}

3. Access state

Previously, access to the state was possible only through class components, which was the main difference between class and functional components. But with the advent of useState, it is possible to manage the state through functional components as well. However in that case we always have to use useState React Hook. From React version 16.8 useState React Hook was introduced to allow developers to write stateful functional components.

Functional component example

// Using functional component with the useState React Hook to handle the state// Without ES6 arrow functionimport React, { useState } from 'react';​function FunctionalComponent() {  const [count, setCount] = useState(0);​  return (    <div>      <p>You clicked {count} times</p>      <button onClick={() => setCount(count + 1)}>        Click me      </button>    </div>  );}

Class component example

// Handling state using the class componentclass ClassComponent extends React.Component {  constructor(props) {    super(props);    this.state = {      count: 0    };  }​  render() {    return (      <div>        <p>You clicked {this.state.count} times</p>        <button onClick={() => this.setState({ count: this.state.count + 1 })}>          Click me        </button>      </div>    );  }}

4. Use of “this” keyword

Whenever we try to access props or state using class components we need to use the “this” keyword. However, it is not necessary to use the “this” keyword for functional components.

Functional component example

function FunctionalComponent(props) {  return <h1>Hello, {props.name}</h1>;}

Class component example

class ClassComponent extends React.Component {  render() {    return <h1>Hello, {this.props.name}</h1>;  }}

5. Lifecycle methods

Lifecycle plays a big role when it comes to the timing of rendering. For class components, we had a method like componentDidMount() that was called immediately after the first render was completed, componentWillMount() that was called before the first rendering, however, this method is considered legacy, so it is not recommended to use this method in newer versions of React and we also had componentDidUpdate() which was invoked immediately after updating occurs. It’s a lifecycle method that runs every time a component gets new props, or a state change happens. This method is not called during the initial rendering.

When we talk about functional components, there is a hook that is great for this purpose. React useEffect Hook serves the same purpose as componentDidMount(), componentDidUpdate() and componentWillUnmount().

Functional component example

import React, { useState, useEffect } from "react";​export default function FunctionalComponent() {  const [data, setData] = useState([]);​  useEffect(() => {    fetch("http://localhost:3001/movies/")      .then(response => response.json())      .then(data => setData(data));  }, []);​  return (    <div>      <ul>        {data.map(el => (          <li key={el.id}>{el.title}</li>        ))}      </ul>    </div>  );}

Class component example

import React, { Component } from "react";​export default class ClassComponent extends Component {  state = { data: [] };​  componentDidMount() {    fetch("http://localhost:3001/movies/")      .then(response => response.json())      .then(data =>        this.setState(() => {          return { data };        })      );  }​  render() {    return (      <div>        <ul>          {this.state.data.map(el => (            <li key={el.id}>{el.title}</li>          ))}        </ul>      </div>    );  }}

Conclusion

How do we decide which component to use? There is no need to decide which components to use, functional components are the way to go. Then why is it important to know these differences if we do not intend to write class components?

The thing is that not so long ago we had class components everywhere. There are still React applications that use class components. This way we will have a generally better understanding of the React library. Also, we will get into a situation to change the code that uses the class components. Certain problems while writing React code via functional components may have already been solved via class components. If we know the class components, we will be able to solve the same problem quickly using functional components.

Knowing the class components is crucial if you are planning to be an amazing React developer.

We invite you to follow us on social networks so you can keep up with all our latest projects and news.