What is the useState Hook in React?

UseState hook is a React hook that is used to add a state to the functional components. A state is basically data that is used to track the application status. The useState hook takes the initial state and returns the current state and function.

Syntax of UseState Hooks:

First, we import the useState into the components at the top as follows

import React, { useState } from "react";

Here is the syntax of usestate

const[state,setState]=useState(initialvalue)

In this syntax, state equals the initial value, which can be an array, function, object, string, number, or boolean. setState in useState is a function that is used to update the value of the state.

useState hook is declared inside the components.

Example of usestate:

Example 1:

Here the first value is the name that is our current state and the second value is setName which is a function used to update the value of the name in our state.

import React,{ useState } from "react";

export default function App() {
  const [name,setName]=useState("Rashid")

  return <h1>{name} is hardworking and good employee</h1>
}

By clicking the button, the state value is changed and updated.

import React, { useState } from "react";
export default function App() {
  const [name,setName]=useState("Rashid")
  return(
      <>
         <h1>{name} is hardworking and good employee</h1>
       <button
        type="button"
        onClick={() => setName("Ahmad")}
      >ChangeName</button>
    </>
   )
}

Toggle the data:

If you want to toggle the Name then we use another function changeName which is used to help in toggle we use if else condition

import React, {useState} from "react";
export default function App() {
  const [name,setName]=useState("Rashid")
const changeName=()=>{
if(name==="Rashid"){
setName("Ahmad")
}
else{
setName("Rashid")
   }
}
  return(
      <>
         <h1>{name} is hardworking and good employee</h1>
       <button
        type="btn"
        onClick={changeName}
      >Toogle the Name</button>
    </>
   )
}

Ternary Operator:

Instead of If else ES6 introduced a ternary operator which works the same as if else.

It is a single line of code.

Now we toggle with the help of a ternary operator

import React,{ useState } from "react";
export default function App() {
  const [name,setName]=useState("rashid")
const changeName=()=>{
(name==="Rashid")?setName("Ahmad"):setName("Rashid")
}
  return(
      <>  
         <h1>{name} is hardworking and good employee</h1>
       <button
        type="btn"
        onClick={changeName}
      >Toogle the Name</button>
    </>
   )
}

Example 2:

If you want to use incrementย  then we also use the useState hookย 

By clicking on the +ย  button the value is incremented.

import React, { useState } from "react";
export default function App() {
  const [incre,setIncre]=useState(0)
  return( 
<>
         <h1>{incre}</h1>
       <button
        type="button"
        onClick={() => setIncre(incre+1)}
      >+</button>
</>
)
}

What Can State Hold:

You can also create many states hook like strings, numbers, booleans, arrays, and object and use them in a single value.

Here is an example:

import React, { useState } from "react";
export default function App() {
  const [name, setName] = useState("Rashid");
  const [education, setEducation] = useState("Infromation Technology");
  const [year, setYear] = useState("2023");
  const [university, setUniveristy] = useState("Pmas Arid Agriculture Univeristy Rawalpindi");
  return(
    <>
      <h1>My name is {name}</h1>
      <p>
        I have completed my {education} from {university} in {year}.
      </p>
    </>
  )
}

useState object:

Now we can also create a single hook that contains an object

ย 

import  React,{ useState } from "react";
export default function App() {
  const [intro, setIntro] = useState({
    name: "Rashid",
    education: "information Technology",
    year: "2023",
    univeristy: "Pmas Arid Agriculture Univeristy Rawalpindi"
  });

  return (
    <>
      <h1>My name is {intro.name}</h1>
      <p>
        I have completed my {intro.education} from {intro.univeristy} in {intro.year}.
      </p>
    </>
  )
}

useState Array:

We use an array map method to show the array in the function components in React. First, we create the array and then declare its value of state in useState after that we use the map method to show the arrayย 

Here is an example:

import React, { useState } from "react";

const bioData=[
  {
  id:0,
  myName:"Rashid",
  age:25
  },
  {
  id:1,
  myName:"Muna",
  age:27
  },
  {
  id:2,
  myName:"Ahmad",
  age:21
  },
  ]

 export default function App() {
const[myarray, setMyarray]=useState(bioData);


const clearArray=()=>{
setMyarray([])
}

 return( 
    <>
     {
       myarray.map((Curelm)=>{
       return<h1> key{Curelm.id} my name is{Curelm.myName} and age is{Curelm.age} </h1>
         })
       }
       <button className="btn" onClick={clearArray}>clearAll</button>
       </>
       )
      }

OUTPUT:

useState Hook

We can also directly use an array in the place of bioData. When click on clearAll it delete all and remain emty array as

Updating Objects and Arrays in useState:

Suppose you want to update one value from the state, which is a name, so other values of the state education, degree, and university will be removed. To overcome this problem we use a spread operator which only updates one value of the state and remains the other values of the state sameย 

Here is an example:

import React, { useState } from "react";

function App() {
  const [intro, setIntro] = useState({
    name: "Rashid",
    education: "information Technology",
    year: "2023",
    univeristy: "Pmas Arid Agriculture Univeristy Rawalpindi"
  });
const updateName=()=>{
setIntro(previousState=>{
return{...previousState, name:"Ahmad"}
});
}
  return (
    <>
      <h1>My name is {intro.name}</h1>
      <p>
        I have completed my {intro.education} from {intro.univeristy} in {intro.year}.
      </p>
       <button
        type="button"
        onClick={updateName}
      >UpdateName</button>
    </>
  )
}
export default App;

When we click the updateName button it only changes the name Rashid to Ahmad.

Alos check the React components and Javascript Array.

About Author

1 thought on โ€œWhat is the useState Hook in React?โ€

Leave a comment