Avi
Avi

Reputation: 11

useState hook setting different value than what is passed into setState()

I have a select menu with some options. When I change the option in select menu I am setting the state of currentValue using setNewValue(event.target.value) and logging the new value of variable to the console.

However the value set for the variable is different from the value I am passing into setNewValue.

const classGrades = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let [classGrade, setClassGrade] = useState(1)
let classSelect = () => {
return (
        <div>
            <select value={classGrade} onChange={(e) => {
                setClassGrade(e.target.value)
                console.log(`I selected ${e.target.value}, so classgrade is now ${classGrade}`)
            }}>
                {classGrades.map(g => <option key={g} value={g}>{g}</option>)}
            </select>
        </div>
    )
} 

Upvotes: 1

Views: 42

Answers (1)

Ahmed Sbai
Ahmed Sbai

Reputation: 16189

This is not how react works, when you update a useState hook its value does not changes immediately, but the component re-render, and in this new render, the value will be updated, so in your case you will not get the new value of classGrade because the component didn't re-rendered yet.

console.log like this :

return (
  <div>
  {console.log('this is a new render ! in the last one I have updated classGrade so for this one its value is :',classGrade)} 
    <select value={classGrade} onChange={(e) => {
        setClassGrade(e.target.value)
        console.log(`I selected ${e.target.value}, but since the component didn't rerenderet yet, classGrade is still ${classGrade} `)
        }}>
        {classGrades.map(g => <option key={g} value={g}>{g}</option>)}
     </select>
  </div>
);

Upvotes: 1

Related Questions