React Functional Components vs Class Components

Jacky Lin
2 min readJan 15, 2021

What is the difference between functional and class components in React?

Introduction to Components:

A component represents the UI (user interface) and the component can be reusable whilst being use in anywhere. There are two main components in React, the first one is the functional component that involves no state inside the component and Class Component that can store state inside the component.

Functional vs Stateless Components:

Both functional and stateless components are JavaScript functions that returns HTML UI. The reason it is called stateless components has to due with the fact that the component is only accepting and displaying data. It accepts properties(props) in function and return html(JSX). With functional components there is no render method.

Lifecycle Method or Lifecycle hooks in functional components

Component lifecycle method can not be used in functional component, because a functional component is just a plain JavaScript function, therefore we cannot use setState() method inside component. Which is why they also get called functional stateless components.

However we can use React Hooks in functional component, by doing that we can use the useEffect() hook that can be used to replicate lifecycle behavior, and useState can be used to store state in a functional component.

Class Component vs Stateful Component

Both components can be used with regular ES6 Classes that extends the component. As well as both class and stateful component can implement both logic and state but they must have render() method returning HTML. If you want to pass down props to class components, it can be used with this.props .

Lifecycle Method or Lifecycle hooks in Class Component

Mounting();

  • When the instance of a component is being created and inserted into the DOM. The 4 methods include constructor(),static getDerivedStateFromProps(),render() and componentDidMount() .

Updating();

  • When a component is being re-rendered it becomes a result of change in either the props or state. It comes with 5 methods that include getDerivedStateFromProps(),shouldComponentUpdate(),render(),getSnapshotUpdate() and componentDidupdate() .

UnMounting();

  • When there is an error during the rendering it comes with two lifecycle getDerivedStateFromProps() and componentDidCatch .

Which one to use?

Benefits to use functional components in React:

  • Functional components are much easier to read and test because functional components is just plain JS function without state or lifecylce hooks.
  • Less Code and more readable for other users

--

--