Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is React setState hook not updating immediately? [duplicate]

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])
like image 734
Natnael Mekonnen Avatar asked Aug 24 '26 06:08

Natnael Mekonnen


1 Answers

Two things you need to know about the state update in React:

  • State is updated asynchronously
  • In any particular render, state and props don't change; changes are only reflected after component re-renders

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.

like image 181
Yousaf Avatar answered Aug 26 '26 19:08

Yousaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!