useState Hook in React

In this article we will learn the very first hook which is the state hook called useState Hook in React. Here we’ll create a simple class component and then try to convert it into the functional component using React Hooks.

Why do we need a hook?

Let’s say you have created a functional component and now you want to use the state variable in this component. So It was necessary to convert this component in class before hooks arrived.

That means react hooks are a new way to access the core features of React without having to use class components.

To understand how the state hook works, we are going to use the simple counter example. First, we will implement the counter with a class component and then implement the same with a functional component and state hook.

Syntax

Use the following syntax for useState Hook. We have to pass the initial value of the state in useState function and it will return the value in the format of the array.

The first argument of the array will provide the value of the state variable and the second argument will be used to update that state.

Example of the useState Hook

  1. Create a react application
  2. Create counter example using class component
  3. Convert counter example using react hook
  4. Output

1. Create a react application

Let’s create a startup application in react using create-react-app. Run the following command to create a react application.

Check out the following article for more information.

Create react application

2. Create counter example using class component

Here, we’ll add a simple button and label to manage the counter where the button will be used to increase the counter and label will be used to display a counter value.

Check out the following code to manage the counter.

ClassCounter.js

3. Convert counter example using react hook

We are going to convert the existing class component to functional with useState hook. So first we will create a simple functional component with label and button.

HookCounter.js

Now we will add the state hook in the above component and handle the button click event.

HookCounter.js

4. Output

Run the code and check the output in the browser.

Output - useState Hook in React - Clue Mediator
Output – useState Hook in React – Clue Mediator

Note:

  • Only call hooks from functional component and don’t call it from regular JavaScript function.
  • Try to avoid hooks inside the loops, conditions and nested functions.

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *