1

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.

Jeff Zivkovic
  • 547
  • 1
  • 4
  • 20
  • 1
    `usename` is a local const. It will never change. When you call setUsername, you're just asking react to rerender the component, not change your local variables. That rerender is asynchronous which is why you'll see people answer that, but the amount of time that passes is not actually important. When the new render happens, a new set of local variables will be created, but they cannot be accessed by code in the previous render – Nicholas Tower Sep 09 '22 at 15:29

0 Answers0