Back to React JS Course

React JS Course

useState is a hook that allow functional components to manage state. In class components this.state holds the state, and you invoke the special method this.setState() to update the state.

It enables to declare state variables with initial values and update them over time. These state variables can hold data that can be changed within the component.

For example,

import React, { useState } from "react"; function Counter() { // Declare a new state variable, which we will call count const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }

Note:

  • The state variable is immutable and readonly.
  • useState() hook and this.setState() (inside class components) update the state variable and the component output asynchronously.
  • Calling the setter function setValue(newValue) of useState() hook (or this.setState() of class components) doesn't exactly update the state, but rather schedules a state update.