I have the following:
const [type, settype] = useState('')
let handleTypeChange = (e) => {
settype(e.target.value)
console.log(type)
}
return (
<div >
<select onChange={handleTypeChange}>
<option value="⬇️ Select a type ⬇️"> -- Select a type -- </option>
{types.map((type) => <option value={type.Id}>{type.name}</option>)}
</select>
</div>
);
}
export default Type;
The issue is that when i check the console there is nothing in the console. Because of asynchronous in react it hasnt set the variable yet, If i do a selection of another value a second time I can see a value .its as if react is trying to catch up.
I even tried settype(x => type) , still didnt work.
If i call settype how can i make sure the value "type" is updated straight away ?
2
Answers
You can use useEffect hook with the "type" dependency to log the updated value, instead of write it in the handleTypeChange function.
In React, state updates with functions like
useState
are asynchronous. When you callsettype(e.target.value)
, React doesn’t immediately update the state variable type. The state update is queued, and React schedules it to be processed later.So, when you log type immediately after calling settype, you’re not logging the updated value. Instead, you’re logging the current value of type, which is the old value because the state update hasn’t yet been applied.
You can use the
useEffect
hook to verify that:You will see that when you select a value from the dropdown the component is rerendered because the state has changed and you will see the correct value of the type variable.
Basically your code is correct, you just shouldn’t expect to log the
type
variable straight away and see the updated value.