React Hooks vs Class Components

In today’s world React has become one of the most popular libraries used by web developers, primarily front end web developers, around the globe. The main reason why it is so preferred is because of its speed and simplicity to reuse code using virtual DOM and components respectively. This post is intended to find out the pros and cons of the topic that revolves around the most fundamental topic of React- STATES!

What is the difference and which one should we select? Before deep diving into the comparison we would first try to understand what are states and how are they used in React, and later we would talk about Hooks and Classes.

How to create a React application?

npx create-react-app myfirstreact

Here npx create-react-app is the basic syntax and myfirstreact is the name of your app(directory).

In the above directory, Counter_Hooks.js and Counter_State.js are 2 files inside the src folder in which we would be implementing the 2 comparisons.

What is state in React?

In simple terms, state is simply an object that contains all your key-value pairs. State determines how your components render and behave. State basically makes your site more dynamic and interactive. One thing that becomes a point of confusion to many is the difference between states and props. States is something that is managed inside of the component, whereas props is something that is passed to the component.

How class manages state in React?

Class components are the default method for the managing of local state in React, but they also lead to side effects and complexity when Life cycle methods come into existence. To access and manage state in a class, you have to initialize this.state as an object within your constructor(), name your local state as a key, and set its initial value as the key’s value. The main problem with class state is deep nested components.

setState() is the default method for updating the state in a class, and this is what causes a component to re-render. It is anyhow recommended to always use setState() when you have to modify your state.

This is how state is declared in classes-

Incase if you have problem with the “super” keyword, just type in the terminal npm install — dev @types/react. Too much of theory! Let’s have a look at an application of class states. Let us implement a simple counter using states.

To set up a class component, you need a fair bit of boilerplate code, which is not limited to your conventional constructor() within your class, and the super() for extending the component. When we pass the event handler function reference as a callback like this (<button type=”button” onClick={this.handleIncrement}>+</button>), we lose the context of this because handleIncrement() becomes just a regular function call without an owner object.

This is the code in the Counter_State.js file-

How React Hooks manage state in React?

The major difference between Hooks and class-based state is that hooks are used inside of the functional component. One thing to keep in mind is that never call hooks inside of a any logic, it should always be on the top level!

useState() is a hook that lets you add a React state to function components. In order to do a fair comparison let us take the same counter example and see how it is any different from the above implementation.

This is how state is declared in functional component using Hooks:-

The way how state is declared in Hooks is const[count, setCount]=useState(0).

This is the basic syntax for Hooks. The first element is the state name and the second variable is a function, analogous to setState() in class based state, that is used to change the state value. The value inside the useState is initial value of the state (count in this case). useState() returns a pair of values in an array, the current state and a function that updates it.

The onClick function can be implemented as — <button onClick={() => setCount(count + 1)}>Click me</button>.

This is how the Counter_Hooks.js file would look like-

Now lets see how to bring these 2 counters on the main screen!

Now get into the App.js and import these 2 files in it. The App.js looks like-

How would the output look like?

In both the cases the output remains the same ( at least the frontend part). Only the method of implementation of states is different.

In order to run the application, open the terminal and move into your react directory using cd command and type in the terminal/command prompt — npm start (Your application will start to run on localhost:3000 by default and you would be directed to see this on the screen)

The first output is that of the class state and the second one is obtained by hooks

Conclusion

Even though React Hooks helped us solve many number of problems, there are still many reasons why one would still prefer class-based states due to the lifecycle methods. There is no hard and fast rule that you should be using Hooks only, but it depends on the individuals convenience and priority.

This article is just to tell you that there are different options that could be explored! Just keep experimenting!

Happy Coding!

-Samarth Nehe

Frontend Web Developer and Competitive Coder!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store