Interview Question: Functional vs Class-Components in React

Interview Question: Functional vs Class-Components in React

In this blog, I want to show you the differences between functional and class components in React.

first, let me give you a brief introduction to React components from the React Documentation

Functional component

import React from "react";

const Demo = props => (
  <div>
    <h1>Hello, {props.name}</h1>
  </div>
);

export default Demo;
  • Functional components are basic JavaScript functions. These are typically arrow functions but can also be created with the regular function keyword.

  • There is no render method used in functional components.

  • Sometimes referred to as “dumb” or “stateless” components as they simply accept data and display them in some form; that is they are mainly responsible for rendering UI.

  • React lifecycle methods (for example, componentDidMount(),render(),componentDidUpdate(),componentWillUnmount(),shouldComponentUpdate()) cannot be used in functional components.

  • Functional components can accept and use props.

Class component

import React, { Component } from "react";

class Demo extends Component {
  constructor(props){
    super(props);
    this.state = {
      myState: true;
    }
  }

  render() {
    return (
      <div>
        <h1>Hello Learner </h1>
      </div>
    );
  }
}

export default Demo;
  • Sometimes called “smart” or “stateful” components as they tend to implement logic and state.

  • React lifecycle methods can be used inside class components (for example, componentDidMount(),render(),componentDidUpdate(),componentWillUnmount(),shouldComponentUpdate()).

  • Class components make use of ES6 class and extend the Component class in React.

  • You pass props down to class components and access them with this.props

Get in touch

Feel free to connect with me on LinkedIn or Twitter !