1

Hey so im facing this strange issue while using react-hook-form.

This is the gist of my code

const [error, setError] = useState(true)

const onSubmit = values => {
    setError(false)
    console.log(error) // true on first click and false on second click
}
<input type="submit" />

As you'll can see I get error as true the first time I click on input and false the second time I click it.

I expect error to be false the first time I click on input does anyone know why it's true?

Note: My form is a nested form where I use FormContext to wrap my form so I can split the form into smaller components. Could it be that that's causing this side-effect or is it just something obvious that I'm missing?

Ziyak
  • 191
  • 4
  • 11

2 Answers2

0

Yep, React is weird like that. setError(false) is running the first time and changing the state, but it's not guaranteed to be synchronous. So the console.log() right after it still has the old state.

React hooks useState not updating with onChange

georgedum
  • 491
  • 3
  • 10
  • Ah thank you! I did solve my issue by ditching useState but was still wondering why useState didn't work. This clears things up. – Ziyak Jun 08 '20 at 19:21
0

React state changes are asynchronous. It is not guaranteed that you will get the most recent change in a synchronous console.log. The correct way of logging the value if you want to see the most recent change would be inside a useEffect hook.

const [error, setError] = useState(true)

useEffect(() => {
  console.log(error)
}, [error]);


subashMahapatra
  • 6,339
  • 1
  • 20
  • 26