useState
set can accept a functionfunction App() {
const [count, setCount] = React.useState(0);
function delayAddOne() {
setTimeout(() => {
// a function gives access to latest previous value
// you don't need to rely on "code" in a closure
setCount(prevCount => prevCount + 1);
}, 1000);
}
return (
<div>
<h1>Count: {count}</h1>
<button onClick={delayAddOne}>+ 1</button>
</div>
);
}
You can learn more building one autocomplete than building a whole website. Both ways are OK though.
— Dan (@dan_abramov) May 20, 2021
https://restcountries.com/v2/name/ukr?fields=name,flags,alpha3Code