How to use useState Hook In ReactJS?

Last updated on October 19, 2022

The useState hook is introduced in React 16.8. It allows developers to manage the local state in a function-based component. The useState hook generates a single state value associated with the component.

There are two types of components in React. One is the class component which is an ES6 class that extends from React and can have state and life cycle methods. The state holds a single value which can be an array or object or any other type. The second is a function-based component where you can use the useState hook to track the state.

In this article, we will be changing the color by clicking the event using useState. To do that we will need to use useState in the component. Let’s get started. Go to react application and open app.js.

To use the useState hook in your component you need to import it. Below script imports the useState hook in the component.

import {useState } from 'react'

Once useState is imported into the complement then we can declare the state variable like below. The first value is ‘state’ which initializes the state and the second value is setState which is a function that will be used for updating state values.

const [state, setState] = useState(initialstate)

function App() {
  const [color, setColor] = useState({color:"Red"});
  return (
    <>
      <h1>My {color}</h1>
    </>
  )
}

In the above example, we have two variables, the first is a color and the second one is a setColor which is a function that will update the color value. The return block of the App method prints the ‘color’ variable that will write the initial value of the color.

Next, let’s create a function that will update the color value on the click event.

  const updateColor = () => {
    setColor(previousState => {
      return { ...previousState, color: "blue" }
    });
  }

In the above function, we are calling the setColor() function that needs the current state. The setColor() function takes the current state value and then overwrites the color value. if the state holds more than color values, those values will remain the same.

Below is an complete example

const { useState } = React
function App() {
  const [color, setColor] = useState({
    color: "red"
  });
   const updateColor = () => {
    setColor(previousState => {
      return { ...previousState, color: "blue" }
    });
  }
  return (
    <>
      <p>
        color is {color} 
      </p>
      <button
        type="button"
        onClick={updateColor}
      >Blue</button>
    </>
  )
}
ReactDOM.render(<App />,
document.getElementById("root"))

Pass Call-Back Function in useState Hook

We can pass the function as an argument in the useState. If the initial state has to be computed and the value returned by the function will be used as the initial state.

For example, we have a function that will return a random number, and that random number we need to use as an initial state value.

const [number, setNumber] = useState(()=>{
  return Math.floor(Math.random() * 100);
})

In the above example, we pass an anonymous function to generate the random number as an initial state value of the number.

Conclusion

To use the useState hook you need to import it into the component. It accepts variables, call-back functions, and an array to update the states.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts