
The useState hook allows you to add state to a functional component. It takes an initial value as an argument and returns an array with two elements: the current state value and a function to update it.
Here’s an example of how to use useState to add a counter to a functional component:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment= () => {
setCount(count + 1);
}
const decrement = () => {
setCount(count - 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>decrement</button>
</div>
);
}
In this example, we start with a count of 0 and update it every time the “Increment” and ‘’decrement’’ button is clicked.