Functional vs Class Components in React


If you understand React, you’ll know that there are basically two ways of writing components in React – the functional components and the class components. The popularity of functional components has been more recently, and there is a reason behind it.

To fully comprehend this difference, you need to gather your understanding as to when to bring in either of the components. But before delving into the core aspects of React, let us first know what is React.

React: The definition and use case

React is a library of JavaScript which is used for developing optimized and interactive user interfaces (UI) for your mobile and web-based applications. The creator of React, Jordan Walke, was a software engineer at Facebook.

  • React is free to use as it is open source
  • React functions using components
  • React is a library for front-end programming offering services for the view part of an application.

In a Model View Controller (MVC) based design, the view layer determines the application’s overall appearance and feel.

What is JSX (JavaScript Syntax Extension)

JSX – is one of the features of React and is used for defining the UI.  It makes debugging and understanding of code simpler by writing structures of HTML in the same code that contains JavaScript.  This ensures that complex DOM structures of JavaScript are brought into implementation.

 

How JSX Is Inseparable Component of React

The first output that is generated after the successful installation of an initial project in React is HTML code. This code is obtained through a JavaScript function that fetches this code from it.

Ideally, frontend-based projects keep codes of JavaScript, CSS, and HTML codes in distinct files. This is not the case in React since the working is different in case of it.

This is because JSX lets you write codes in both JavaScript and HTML together in a single file though you have the option of writing CSS code into another file.

JSX is very flexible since you get to run any JavaScript program such as (logic, routines, variables, and so on) inside the HTML code through curly braces.

 

Defining a Component

Components in React are self-regulating, reusable block of code which splits the UI into bits. Instead of developing the entire UI in a single file, you can split the divide all the units into independent pieces.

In other words, when you develop a  web application  using React, it is created in the form of numerous small and separate snippets of code which are known as React components. There are basically two kinds of components –

 

  • Functional Components
  • Class Components

 

Functional Vs. Class Component in React

Before outlining the differences between the two, let us find out how the two components functioned before the launch of Hook. Earlier, functional components were used to render JSX for displaying content to the user.

In the case of class components, the rendering was done by utilizing the state system or the lifecycle method system.  Let us find how the two components are different from each other-

How JSX Is Rendered For Displaying Content

JSX is an abbreviation for JavaScript XML. It lets you code HTML elements in JavaScript and put them in the DOM without utilizing appendChild() and createElement() functions. DOM (document object model) is a software design interface for HTML and XML documents.

It denotes the page on which the programs perform modifications such as document content, structure, and style.  The document representation by DOM is done in the form of objects and nodes. The DOM represents an object-oriented version of the web page, which can be altered using a scripting language, e.g., JavaScript.

 

Rendering JSX in a class component

In Class Components

The rendering of functions or methods is done through ES6 classes. These are special classes that are used for formalizing the general JavaScript pattern of acting like class inheritance hierarchies using methods and examples. There is another way of achieving the same output through destructuring.

Let us list out few key points of functional components-

Class Component

  • It is a common ES6 classes that extends component class through a library in React.
  • The other name is the “stateful” component since it applies to state and logic.
  • It requires the function render () in order to return HTML.
  • The logic used for creating UI is complex.
  • Props are passed to class components and are accessed through this. props

 

Rendering JSX in Functional Components

Functional components are also known as stateless components, which are JavaScript functions that return JSX.

Let us list out few key points of functional components-

  • It is also known as a “stateless” component since it takes data as input and displays it in the form, which helps in the rendering of the UI.
  • It accepts props (properties) in functions and returns html (JSX).
  • It offers results without using state.
  • It is a JavaScript method that returns an html UI.
  • It does not require using the render function.

 

Functions in React: Lifecycle method in Class Component

There are four stages in which class component’s lifecycle hooks are classified-

Stage 1: Mounting()

  • It is done whenever a single occurrence of a component is generated and placed into the DOM.
  • It consists of four method constructor such as – render() , componentDidMount(), static getDerivedStateFromProps() and a.constructor(props).
  • render()-when the state of the component relies on modifications.
  • componentDidMount()-it is called instantly after a component and its sub-components have been rendered to the DOM
  • static getDerivedStateFromProps(props, state)-when the state of the component depends on changes
  • constructor (props)-a dedicated function that will get invoked every time a fresh component is generated.
  • Preparing the state that binds the event handler.
  • super(props) that directly overites this.state.

 

Stage 2: Updating()

  • used whenever re-rendering of a component takes place resulting from a modification performed either to state or its props.
  • Consists of 5 lifecycle such as -staticgetDerivedStateFromProps(),shouldComponentUpdate(),render(),getSnapshotUpdate() and componentDidupdate()
  • getDerivedStateFromProps()-it is the first method invoked during a component gets updated.
  • This is the default setting to place the state object depending on the startingl props.
  • shouldComponentUpdate()- this method returns the output as a Boolean value which states whether React should proceed with the rendering process continue or discontinue.
  • It holds the default value is true.
  • getSnapshotBeforeUpdate()-this method gives you access to state and props prior to updating.
  • This means regardless of updating or not, and you can check the values before the update.
  • getSnapshotBeforeUpdate() if this function exists, then you should also take in the componentDidUpdate() function to avoid any kind of errors.
  • componentDidUpdate()-this method is invoked after the updating of the component in the DOM.

Stage 3: UnMounting

  • Utilized on the removal of the component from the DOM.
  • Consists of 1 lifecycle componentWillUnmount()

Stage 4: Error Handling

  • Used every time an error occurs at the time of rendering.
  • Consists of 2 lifecycle- static getDerivedStateFromProps() and componentDidCatch.

Functions in React: Lifecycle Method in Functional Component

  • Component based lifecycle functions are not present in case of functional component.
  • This is because a functional component is nothing but mere simple JavaScript function. Therefore you cannot use setState() function inside the component.
  • This is the reason they are known as stateless components.
  • However, you make use of React Hooks such as useEffect() for replicating lifecycle characteristics.
  • You can also utilize useState for storing a state in a functional component.

Why do Functional Components win Over Class Component?

Advantages of using functional components –

  • Functional components are easy to work with and read since they are simple plain JavaScript functions devoid of any lifecycle hooks or state.
  • The readability is better due to the lesser code.
  • It will be quite easy to segregate presentational and container components.
  • This is because you need to be more watchful of the state of your component in case you are not having access to setState().

 

Bottom Line

If you are coding for a presentational component that does not have a state of its own or requires accessing a lifecycle hook? Then you should definitely use more and more functional components.  However, for handling states, you can utilize the class component.

React Functional Components are the de facto tool if you want to write the latest modern React applications. There have been a lot of different kinds of components available earlier. However, with the launch of React Hooks, it is possible for you to program your whole application with just methods in the form of React components.

Our React experts can code your ideas into a market-ready product, need an expert hand, get in touch!