What is useState Hook?

In this article, we will continue our React JS journey. We will see more about the useState hook.

What is the useState hook?

useState is an accept an argument that is the initial state of the property and returns a pair of values. 
Which are the current value of the state value property and method that has the ability to update or change the current state value. We will look at syntax when we talk about examples.

Rules to use the hook.

1. Only called Hooks at the top level.  This means you must write the useState hook at the top level of the react functional component.
2. Don't call Hooks inside loops, conditions, or nested functions.
3. Only call Hooks from React Functions. This means you should not call hooks from regular JavaScript functions.

Now, Let's jump into the practical example so you have a clear picture.

We will write a simple counter component that increases a counter value at the click of a button. 
There were three steps:

1. React a functional component called "ReactUseStateSingleDataType".
2. Write a "useState" hook that accepts an initial value as an argument and returns pairs of values that is current value and a method that has the ability to update the current state.
3. Write a "handleClick" function that has the ability to increase a counter of the current state.

Step 1:-
 const ReactUseStateSingleDataType = () => {
   return <div>ReactUseStateSingleDataType</div>;
 };
 export default ReactUseStateSingleDataType;


Step 2:-
 import React, { useState } from "react";
 const ReactUseStateSingleDataType = () => {
   const [count, setCount] = useState(0);

   return <div>{count}</div>;
 };

 export default ReactUseStateSingleDataType;

Here, you can see that use zero(0) as the "initial value", "count" as the current value, and "setCount" as a method that is responsible for changing the current value. Make sure you have imported the useState hook from 'react'.

Step 3:-
 import React, { useState } from "react";
 const ReactUseStateSingleDataType = () => {
   const [count, setCount] = useState(0);
   const handleButtonClick = () => {
     setCount(count + 1);
   };

   return (
     <div>
       {count}
       <br />
       <button onClick={handleButtonClick}>Increase Count</button>
     </div>
   );
 };
 export default ReactUseStateSingleDataType;
Here, you can see in jsx a button with "Increase count" text. That has bind onClick event with a function that can increase a current state value by setting set count(count + 1);
basically when you click on the button "handleButtonClick" function is called and setCount method takes the current state value adds one to it and sets it back to the current state.

This Example is all about useState which has only accepted a Number, String, and Boolean dataTypes.

To access the code, please click here.

Comment below if you have any queries related to the above tutorial for a What is useState Hook?.

Post a Comment

0 Comments