Go Green One tree
One life
Trees
Loading...

React Classes vs Functions: Which One To Use?

Author
SPEC INDIA
Posted

July 11, 2023

Category React

Before React components, development was like a nightmare for today’s developers, thousands of lines of code when developing a single-page application put together a single file of conventional DOM structure. The worst was the thought of modifying or updating that file.

Today’s ReactJS development companies can have a sigh of relief with the introduction of components especially Hook in React version 16.8.

React Components are often referred to as wall’s brick-logical, independent, and reusable code pieces of application which simplify User Interface (UI) creation. These components can either be React Class or Function which accepts props(properties are a type of object) and returns a React element.

This is where the debate starts amongst the React.js community of React functional components vs class components.

Before we jump into knowing about React classes vs functions, let us first understand them individually.

React-Classes-vs-Functions

What is a Functional Component?

React’s Functional Component is a JavaScript function (functions may or may not include parameters that contain data) which only returns JavaScript XML (JSX) elements. These presentational components used by ReactJS developers are mainly responsible for rendering UI. Known as stateless components, the React functional components can also implement states after the introduction of Hooks with the useState() hook which not enables the component to track their state.

“Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.” – reactjs.org

Known for a substantially lesser amount of code, these components can accept and use props(properties). React lifecycle methods and render method(componentWillMount(), componentDidMount(), or render()) are not used in the React functional components.

Class component in React are slightly different from React functional components, let us find out more about the class components.

What is a Class Component?

Unlike the React functional components, to return React elements this ECMAScript 6 (ES6) JavaScript class (Class component in React) needs to extend React. Component along with creating a render function.

When it comes to features ReactJS Class has more to offer as it includes constructors, life cycle methods, render functions, and state/data management making these React components more powerful and versatile. As the Class component in React is “stateful” the ease the management/handling of state/user events.

Now, let us see get insights to React functional components vs class components on some of the crucial aspects.

Handling State

The state in React is used by ReactJs programmers to manage component actions. Handling the state was only possible with React Class component until the introduction of Hooks in React 16.8 which enables the React experts to create stateful functional components in React.

Functional Component:

As seen in the example below of the basic counter, to handle the state in the function component useState() Hook is used.
Here UseState Hook accepts the initial state which can be any type supported by JavaScript like strings, objects and null, in our case it is 0. Further with the use of setCount() methods on each click of the button the counter would increase and the component would return the number.

Handling-state-functional-component

Class Component:

In the case of the Class component, the use of the setState() function is done for executing a similar logic. To begin with, a constructor is to be defined to create a state object with a state key and initial value (() here).

To update the value of count this.state.count is used in the setState() function of the render() method. Like the functional component, the class component would display the number of times a button was clicked but the line of code is more than the former one.

Handling-state-class-component

The winner of React functional components vs class components or preferable React Component in case of handling state is React functional components.

Lifecycle Methods

The React Components have a lifecycle during which they go through phases like Initialization, Mounting, Updating, and Unmounting. There are predefined methods that the React developers can use to invoke each of these phases. These methods enable the ReactJS geeks to manage the side effects.

Functional Component:

As these lifecycle methods can only be written in class, there were no lifecycle methods in functional components until the introduction of Hooks.

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. – React

So, unlike different methods for each phase of the lifecycle in React class component, for the functional component, you can use one hook useEffect to manage the side effects like fetching data or managing subscriptions.

Here is the example of the mount and unmount lifecycle phase with the use of useEffect Hook with an empty dependency array ([]) and a cleanup function returned respectively.

Lifecycle-method-functional-component

Similarly, for componentDidUpdate, you must use useEffect Hook with a dependency array containing state/prop values to check for any update. In the functional component, for shouldComponentUpdate there is React.memo or useMemo Hook. To update the state based on props (getDerivedStateFromProps) in the function component, you can use useMemo or useEffect Hook.

Class Component:

To invoke the same phases of the lifecycle methods – mount and unmount in React class component, ReactJS developers have to use two separate methods componentDidMount() and componentWillUnmount().

Lifecycle-method-class-component

In the case of lifecycle methods, for React functional vs class components, the Functional class in React leads in terms of its Simplicity.

Props

Abbreviation of ‘Properties’, props are read-only and immutable objects which store a value (objects, arrays, and functions). These arbitrary inputs are passed to the component via HTML attributes just as an argument in a function. These objects are used by the React component to communicate/transfer data with each other.

Let us find out how these props are passed in in each of these React components.

Functional Component:

In a Functional component, a prop is passed as an argument to the function.

props-functional-component

Class Component:

While in React class component, the props here are props objects which can be accessed via this keyword since class components extend React.Component.

props-class-component

As it is easier to pass props in functional components with Hooks, for React class vs functional component, functional beats the class component.

React Hooks

One of the major differences which enable Functional components in React to gain popularity over the class is to the extent that the React coders started assuming that class components are outdated and almost on the verge of removal. Even the official documentation of React has mentioned that” There are no plans to remove classes from React.”

Functional Component:

Hooks are simple backward-compatible JavaScript functions which enable the functional components to use across various React features like state and lifecycle methods which were previously available only in class components.

Here are some of the most essential React hooks:

  • useState Hook: enables React develops to track/manage local state
  • useEffect Hook: lets RecatJS developer perform side effects (setting up a subscription, Data fetching, manually changing the DOM, etc)
  • useMemo Hook: returns a memorized value (the result of a calculation between re-renders)
  • useContext Hook: manage state globally
  • useRef Hook: returns a mutable ref object
  • useReducer Hook: alternative to useState
  • useCallback Hook: returns a memorized callback function

react-hooks -functional-component

Class Component:

Hooks can’t be used inside a class.

React Classes vs Functions: A Tabular Comparison

Functional Components Class Components
Extend from React.Component Don’t extend from React.Component
Stateless components Stateful components
 Do not have any Lifecycle Methods, uses React hooks instead introduced in React in version 16.8 Has different life cycle methods for invoking different phases of component lifecycle
Fewer lines of code Lengthier code lines
Don’t maintain state information Maintains state information
Do not use any render method Use render() method
Functional components eliminate the use of the “this” keyword Class components use the “this” keyword
Don’t support a constructor Require a constructor as the state needs to be stored
Support React 16.8 Hooks Don’t Support React 16.8 Hooks
Functional components are more efficient Class components are a little inefficient
Uses React Hooks to manage state Has built-in state management using this.state
Props are passed as a parameter to the function Props are accessed through this.props
Help developers to use best practices Easier to cause performance issues
React requires less work to render these components. React requires more work to render these components.
Easier to read and test Harder to read and test
Uses less memory Uses more memory
Supports inheritance design patterns Promotes composition

React Classes vs Functions: Concluding Thoughts

With the introduction of React Hooks the popularity of React functional components has grown tremendously so much so that the Class components have turned out to be obsolete. However, though the functional components offer simplicity and faster development the Class component in React increases the code reusability and features when developing high-quality front-ends. The unique aspect is the Error Boundaries exclusive to the class component.

Depending on the requirements the ReactJs developers can choose either of these components.

Here are some recommendations that would help you to make a more informed decision about choosing between the React class component vs functional component.

When to use Class Component in React?

The developer can use the Class Component in the following scenario:

  • For developing large and complex components like tables, models, or forms
  • To build reusable components to be used in multiple parts of your application
  • To build complex components/legacy code that requires state or lifecycle methods.
  • For building container components
  • When using third-party libraries that require class components
When to use React Functional Components?

The developer can use the Functional Component in the following scenario:

  • Recommended for new projects/components
  • To develop simple components that do not require state/lifecycle methods
  • For building components like buttons, labels, or input fields
  • For building presentational components
spec author logo
Author
SPEC INDIA

SPEC INDIA, as your single stop IT partner has been successfully implementing a bouquet of diverse solutions and services all over the globe, proving its mettle as an ISO 9001:2015 certified IT solutions organization. With efficient project management practices, international standards to comply, flexible engagement models and superior infrastructure, SPEC INDIA is a customer’s delight. Our skilled technical resources are apt at putting thoughts in a perspective by offering value-added reads for all.

Delivering Digital Outcomes To Accelerate Growth
Let’s Talk