简体   繁体   中英

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.

The main reason behind this behavior is setState is asynchronous so the changes should not be expected immediately.

Specially for this cases there is a hook called useEffect() to capture changes on state. If you add categoryId into the dependency array of useEffect then it will be trigger once you have change on that state. Thus you can log your changes as the following:

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

Suggested read is Using the Effect Hook .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM