By default, a React component is only executed once. In an application that displays a price and should change the displayed price when a button is clicked, we need a mechanism to update the component and display the new price.
Here comes the useState() hook into play.
Example of Changing a Price
//App.jsx
import { useState } from 'react'
import './App.css'
function App() {
const [price, setprice] = useState('100');
function handleClick(){
setprice('75');
}
return (
<div>
<p data-testid="price">{price}$</p>
<button onClick={() => handleClick()}>Apply Discount</button>
</div>
);
}
export default App
In the call to useState(), the initial value (100) is passed. The variable price represents the current value, while setPrice is a function used to update this value.
Important Notes
- The
useState()hook must be called directly within a React component – not inside loops or nested functions. - If in the
handleClickfunction you immediately access the value ofpriceright after callingsetPrice, it will still show the old value because the update has not yet occurred.