Understand the concept of useState() in ReactJs

Understand the concept of useState() in ReactJs

The useState Hook in ReactJs allows you to implement the state variable without using a class-based component.

First, to use the useState Hook, you import it from 'react'

import { useState } from 'react

The useState function takes two arguments; an initial state and it returns an array of two entries (the current state and the function that updates the state).

 const [count, setCount] = useState(0);
import {useState} from 'react'

function NumberChange() {
 const [count, setCount] = useState(0);
}

from the code above, the count is the current state while the setCount function is used to update our state.

We then set our initial state to zero useState(0)

Let us look at an example. We will change the number from its initial value of zero (0) to another value.

import { useState } from "react";

function NumberChange() {
  const [count, setCount] = useState(0);

  return <h1>The First Number is  {count}</h1>
}

Now, let's update the state

import { useState } from 'react'

function NumberChange() {
 const[count, setCount] = useState(0);

return(
    <div>
             <h1>The First Number is  {count}</h1>
             <button onClick = {() => 
                    setCount(1);
                }></button>
    </div>
)

}