Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks State update one step behind. For this reason my changes are not working correctly

I want to see the changes in the use of react hooks on state immediately. My changes are one step behind on state. How can I solve this.

const [categoryID, setCategoryID] = useState(0);

const changeCategory = (e) => {
    setCategoryID(e.target.value);
    console.log(categoryID);
  };

<Field
     as="select"
     onChange={changeCategory}
     style={formStyle().inputStyle}
     className="form-control"
     type="text"
     name="categoryID"
      >

When I select the first value, the result appears 0. If I chose my second value, I see the value I chose first on the console.

like image 982
Gucal Avatar asked Feb 01 '26 03:02

Gucal


1 Answers

State change is asynchronous in react hooks hence there is no guarantee that the state will be updated just after setting it. For this reason we have useEffect to the rescue that accepts a dependency and will be executed after that dependency is changed.

Example-

useEffect(() => {
  console.log(categoryID);
},[categoryID])

Now in this case the dependency is categoryID and whenever it's value is changed the function will be executed and will console the updated value.

like image 66
maya_nk99 Avatar answered Feb 02 '26 17:02

maya_nk99



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!