Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

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

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>
    )
}

1 Answer

Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 48,723 Points

Hey Abhimanu,,

Try the below:

import React, { useState } from 'react' // useState needs to be imported
const classGrades = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
export const ClassSelect = () => { // name should be PascalCase
let [classGrade, setClassGrade] = useState(1) // this needs to be in the component function as per hook rules
return (
        <div>
            <select value={classGrade} onChange={(e) => {
                setClassGrade(e.target.value)
                console.log(`I selected ${e.target.value}`)
            }}>
                {console.log(`so classgrade is now ${classGrade}`)}
                {classGrades.map(g => <option key={g} value={g}>{g}</option>)}
            </select>
        </div>
    )
}

I think that in the callback classGrade is still the previous vailue.... If you add console logs as above, you'll see it is the correct value.

Hook rules reference: https://legacy.reactjs.org/docs/hooks-rules.html