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

Development Tools

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 (
            <select value={classGrade} onChange={(e) => {
                console.log(`I selected ${e.target.value}, so classgrade is now ${classGrade}`)
                {classGrades.map(g => <option key={g} value={g}>{g}</option>)}

1 Answer

Clayton Perszyk
Clayton Perszyk
Treehouse Moderator 48,837 Points

Looks like the issue is this:

useStateis an asynchronous hook and it doesnโ€™t change the state immediately, it has to wait for the component to re-render.

see this article for more info: https://javascript.plainenglish.io/why-you-shouldnt-always-use-usestate-658994693018#:~:text=TL%3BDR%3A%20useState%20is%20an,t%20trigger%20a%20re%2Drender.