Throughout my application I am modifying state through useState()
, for example:
const [question, setQuestion] = useState('')
const updateQuestionHandler = () => {
let honestQuestion = 'is this a race condition?'
setQuestion(honestQuestion)
console.log(question) // Returns => '' or the previous state, why isn't the updated state returned instead?
}
return (
<div>
<p> { question } </p> // This is generally updated correctly, after the button click below
<button onClick={() => updateQuestionHandler()}> Click to update question </button>
</div>
)
What is happening above is, once I update state with setQuestion(variable)
, the state gets updated (eventually). How can I ensure that the state has been updated and is safe for reference after setting it?
You can see where I try to console.log()
the updated state, right after setting it, the previous or old state gets returned. I could instead console.log(honestQuestion)
, is that the correct thing to do? I feel like I should be using state as the single source of truth.