React useState setter not updating

Viewed 14

My code:

export function ChangeUsername() {
    const inputRef = React.useRef();
    const [username, setUsername] = React.useState("Default");

    function clickHandler() { 
        const newUsername = inputRef.current.value; 
        console.log(newUsername);       
        setUsername(newUsername);
        console.log(username);
    }

    return (
        <div>
            <button onClick={clickHandler}>Change Username</button>
            <input type="text" ref={inputRef} />
            <Username value={username} />
        </div>
    );
}

In the dev browser, I enter "Joe" into the input field and click the button.

I expect to see "Joe", then "Joe" in the console. I see "Joe", then "Default".

I've read in a few other questions the useState works asynchronously, which seems to explain this behavior. But I've tried async/await and a few other methods to check the username later. I always get "default" as the value of username.

Thanks in advance for any insight.

0 Answers
Related