What is a Hook? A Hook is a special function or in-built function that lets you “hook into” React features. For instance, useState is a Hook that lets you add React state to functional components.

When should we use a Hook? If you have a functional component and realize that you need to add some state to it. Back in the days, you had to convert that functional component to a class component. With the release in February 2019 of React 16.8 we no longer need to convert function to class component, you can now use a Hook inside the existing function component in order to get some state.

In this tutorial, you are going to learn useState by comparing this functional component to an equivalent class component.

Equivalent Class Component

First things first, we need to import ‘useState’ Hook from react which will be invoked inside our function in order to get some state.

Declaring a State Variable

In our class component, we initialize the count state to 0 by setting this.state to {count : 0 } in the constructor:

In our function component, since we have no this we call the useState Hook directly inside our function to declare our state variable:

What does useState do? useState has the exact same capabilities that this.state provides in a class. It declares a “state variable”, in this example our variable is called count and setCount is the function which will be used to update our state variable.

What should we need to pass to useState as an argument? The only argument to pass to the useState Hook is the initial state and it could be number or a string unlike with classes, where the state should be an object.

What does useState return? It returns a pair of values: the current state and a function that updates it. In our example, we declare a state variable called count and set it to 0. SetCount is a function we will using to updates the current count.

Reading State

When we want to display the current count in a class, we read this.state.count:

In a function, we can use count directly:

Updating State

In a class, we need to call this.setState() to update the count state:

In a function, we already have setCount() and this is a one we will invoke to change count state:

We can also create another function which sole purpose once invoked is to update the state. For this time around let’s call that function ‘handleChange’ and inside that function we will call the function setCount to change the state:

I hope you enjoyed reading through this tutorial.

resources:

https://reactjs.org/docs/hooks-state.html

https://www.smashingmagazine.com/2020/04/react-hooks-api-guide/

Full Stack Software Engineer