Search code examples
typescriptinputevent-handlingonchangeuse-state

onChange input delay in React


I've never really noticed this before; not sure if theres a bug in my code or if onChange always behaves this way, but I'm getting an input delay and am not sure how to resolve it. Heres an example of what I mean:

enter image description here

As you can see the console only prints the previous state which is a nuisance because that means to have the user log in they have to click the "Go" button twice for it to receive the correct state, even if the username and password has been correctly input.

My code is fairly straight forward:

const [state, setState] = useState<LoginStateType>(iLoginState)
const {username, password} = state

const handleChange = (event: ChangeEventType) => {
    const {name, value} = event.target
    setState({...state, [name]: value})
    console.log(username)
}

{...}

<input type="text" name="username" value={username} onChange={handleChange}/>
<input type="text" name="password" value={password} onChange={handleChange}/>

Any help is appreciated, thanks!


Solution

  • Since State Updates May Be Asynchronous.


    With hooks, this can be achieved by

    const [state, setState] = useState(/* ... */)
    
    setState(/* ... */)
    
    useEffect(() => {
      // state is guaranteed to be what you want
    }, [state])