DEV Community


React Functional over Class components ? 🤔

elukuro profile image Heru Hartanto ・1 min read

Component is a reusable part that should be able to use anywhere inside user interface.

There are two way to create component, first using functional component and second using class component, I prefer using functional except when I need using state management or take benefit from lifecycle, here is why

Functional component or stateless component

  • Just function that return HTML
  • Give solution without managing state and able to consume props
    function Hey(props){
        return <h1> hello {}</h1>
    export default Hey
Enter fullscreen mode Exit fullscreen mode
  • No render method, just return
  • Component lifecycle such as mounting and updating doesn't exist, instead functional component using useEffect() to replicate lifecycle behavior, and useState() to store state

Class component or stateful component

  • Classes that extends component class from react library
  • Managing state this.setState and able to consume props with this.props
  • Have render() method, and must using it to render HTML
  • Have three phases of lifecycle there is mounting, updating, unmounting
    • Mounting: when putting elements into the DOM (constructor, getDrivedStateFromProps, render, componentDidMount)
    • Updating: when component is updated (getDerivedStateFromProps, shouldComponentUpdate, render, getSnapshotBeforeUpdate, componentDidUpdate)
    • Unmounting: when component remove from the DOM (componentWillUnmount)
    import React, { Component } from "react";
    class Hey extends Component{
        constructor(props) {
            this.state = {
        render() {
               <h1> Hey {} </h1>
    export default Hey
Enter fullscreen mode Exit fullscreen mode

So why functional components ?

  • Less code
  • More readable because it's like a plain javascript function
  • More easy to separate from container


If you don't need your own state or access lifecycle, use functional component as much as possible

Discussion (0)

Forem Open with the Forem app