I am trying to call a handler from a parent function with the updated state value as an argument, however, the state does not update immediately after the setSelected is called as both console logs are printing false(the initial value). After the onClick function is completed however, it gets updated.
onClick={() => {
console.log("Clicked: ", props.rank, props.suit, selected);
setSelected(!selected)
console.log("selected: ", selected)
// props.handle_card_selected(props.id, selected)
}}
useEffect(() => {
const check_border = () => {
if (selected) {
return "green"
}
return "black"
}
check_border()
}, [selected])
Two things you need to know about the state update in React:
If you want to log the updated value of selected, put the log statement in the useEffect hook.
You can't update and log the updated value of any state variable in the same render; component will have to re-render to reflect changes due to state update.
Similarly, if you want to call a function with the updated value of selected, call the function from inside the useEffect hook.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With