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.
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.
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