useState
is a React hook used for State Management in a component. The useState
hook is a function that takes the initial state as an argument and returns an array of two entries.
const [state, setState] = useState(initialValue)
Here, state
is a variable that will store the value and setState()
is a function that will modify the value. An initial value is passed to useState
. The initial value can be of any type.
import React, {useState} from 'react' //import the useState
function Example() {
const [value, setValue] = useState(0) //initialize useState
const handleDecrement = () => {
setValue(value - 1); // modify state
}
const handleIncrement = () => {
setValue(value + 1) //modify state
}
return (
<div>
<button onClick={handleDecrement}>-</button>
<span>{value}</span> // read state
<button onClick={handleIncrement}>+</button>
</div>
)
}
export default Example