0

So I've been working with react for a while now, and I've noticed this weird behavior when I use the method setState provided by the useState hook, when I update the value of a piece of state using setState and I reference that state immediately after updating it, it give me the previous value of the state before updating but it shows correctly when I display the state in the DOM.

<TextField
    label="Username"
    value={handle}
    error={error.hasError}
    id="username"
    onChange={e => {
        setHandle(e.target.value);
        console.log("Ran");
        for (let i = 0; i < e.target.value.length; i++) {
            if (!isAllowedChar(handle[i]))
                return setError({
                    message: "Username should only contain alphabets, digits, _ and .",
                    hasError: true,
                });
            setError({ message: "", hasError: false });
        }
    }}
/>

when I begin typing in the input field, the onChange handler updates on each key stroke as expected and prints ran to the console, the value of the input field updates correctly on each keystroke as expected but the next bit of code where I reference the state handle after updating it with setHandle it gives me the previous state so my conditions are not satisfied until after another keystroke even if there is an error on the previous keystroke.

I would like to know if there's something I'm doing wrong or if it's just a weird bug in useState

2 Answers2

1

State Updates May Be Asynchronous. It is mentioned clearly in the React docs: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous If you still question why setState is asynchronous, can check this thread: In ReactJS, why does `setState` behave differently when called synchronously?

Nhut Dinh Ba
  • 354
  • 1
  • 6
0

If your application is not working as expected because it's not updating the state fast enough, you can 'wait' for it to update with useEffect hooks.

joaoricardotg
  • 137
  • 3
  • 9