The useState hook allows functional components in React to store and manage data that can change over time. It is simple to use and ideal for handling basic state updates within a component.
- It lets you add state variables to functional components.
- It is best suited for simple and straightforward state updates.
- The hook must be imported from React before using it.
Syntax
const [state, setState] = useState(initialState)
- state: It is the value of the current state.
- setState: It is the function that is used to update the state.
- initialState: It is the initial value of the state.
Example:
import { useState } from "react"
function Count() {
const [count, setCount] = useState(0);
function incerement () {
setCount(count+1)
}
function decerement() {
setCount(count-1)
}
function reset() {
setCount(0)
}
return(
<div>
<h1>Counter app</h1>
<h3>count: {count}</h3>
<button onClick={incerement}>+</button>
<button onClick={decerement}>-</button>
<button onClick={reset}>reset</button>
</div>
)
}
export default Count

Top comments (0)