Difference between class component and functional component in react js
React

Difference between class component and functional component in react js

SI

Shamal Iroshan

2021-07-14 | 4 min read

In react there are two ways to create components, those are functional components and class components. However, after version 16.8 of React, functional components are getting more popular. You will be able to find reasons for that from this article.

1. Syntax difference

The first difference that we can see between these two components is, functional components are just java functions that return JSX. A class component is a JavaScript class that extends React.Component which returns JSX in its render method. Let's see these differences from the code examples.

Functional componnet

import React from "react";

function FunctionalComponent() {
	return "Hello world";
}

Functional component with ES6 arrow functions

import React from "react";

const FunctionalComponent = () => {
	return "Hello world";
};

Class component

import React, { Component } from "react";

class ClassComponent extends Component {
	render() {
		 return "Hello world";
	}
}

2. Handling state

n a react project we can not avoid using state variables but this was only possible in react class components before react version 16.8. But after this version developers got a chance to develop stateful functional components using React hook useState. Learn more about react hooks from here

State handling in functional component

function Example() {
const [count, setCount] = React.useState(0);

	return (
		<div>
			<p>You clicked {count} times</p>
				<button onClick={() =&gt; setCount(count + 1)}>
				Click me
			</button>
		</div>
	);
}

To use state in a functional component we need to use useState Hook. useSatte returns the current state and a function that updates it. If it's a bit confusing you can consider count as the state variable and setCount as the setter for that state variable.

In useState we can use any data type JavaScript allows such as int, string, null, object.

State handling in class component

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() =&gt; this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

A class component handles react states a bit differently. First read about React.Component from here.

If we implement a constructor and don't call super(props), all the state variables that you are trying to use will be undefined.

To use the state in the class component we need to create a state object with state key and value, after that inside the JSX we can use this.state.count to access the state variable.

3. Passing props

Let's pass a prop named age to ExampleComponent.

<ExampleComponent age=25  />

Props with functional component

const ExampleComponent = (props) => {
	return <h1&>Age is:  {props.age}</h1>;
};

We pass props to functional components as an argument.

Props with class component

class ExampleComponent extends React.Component {
  render() {
    const { age } = this.props;
    return <h1>Age is: { age }</h1>;
 }
}

Because this is a class we need to use this keyword to access props. Also, notice here we use destructuring to get the value of age prop.

4. Lifecycle methods

We all know lifecycle methods play a major role in the timing of component rendering. We can use methods like componentDidMount() to handle lifecycle in class components and hooks to handle lifecycle in functional components.

On mounting

We can use the componentDidMount() method to handle codes that need to run on mounting. But this is only for class components.

class ClassComponent extends React.Component {
 componentDidMount() {
   console.log("Hello");
 }

 render() {
   return <h1>Hello, World</h1>;
 }
}

As a replacement for the componentDidMount method, we can use the useEffect hook in the react functional components. We use the useEffect hook with the second argument of []. The second argument of the useState hook is normally an array of a state(s) that changes and useEffect will be only called on these selected changes. But when it’s an empty array like this example, it will be called once on mounting.

const FunctionalComponent = () => {
	 React.useEffect(() => {
	   console.log("Hello");
	 }, []);
	 
	 return <h1>Hello, World</h1>;
};

On unmounting

In class components, we can use componentWillUnmount method to run codes on unmounting.

class ClassComponent extends React.Component {
     componentWillUnmount() {
       console.log("Bye");
     }
    
     render() {
       return <h1>Bye, World</h1>;
     }
}

we can use a useState hook for unmounting as well. But be careful, the syntax is a bit different. What we need to do is return a function that runs on unmounting inside the useEffect function. One advantage of using useEffect is that we can write functions for both mounting and unmounting in the same place.

const FunctionalComponent = () =>{
	    React.useEffect(() => {
	       return () => {
	         console.log("Bye");
	       };
	    }, []);
    return <h1>Bye, World</h1>;
};

Thank you for reading my post and I hope you find some useful things from here.