https://codesandbox.io/s/busy-lamport-lfqwt?file=/src/App.js:0-678
Using a state hook
const [loading, _setLoading] = useState(false)
A button needs to be disabled based on the the state above
return (
<div className="App">
<button type="button"
onClick={handleSubmit}
disabled={loading}> Send </button>
</div>
);
The eventhandler is
async function handleSubmit(event) {
setLoading(true)
console.log(loadingRef.current)
await setTimeout( () => {} , 3000)
setLoading(false)
console.log(loadingRef.current)
}
The button needs to be disabled while setTimeout waits for three seconds
React stores the default loading state in a closure when running the event handler later. So I use a useRef to access current value inside the handler ( not related with what needs to be achieved which is..) how to disable the button for three seconds based on the loading state.