Search code examples
reactjsreact-hooksuse-statereact-lifecycle

React console.log(i) print the previews result


With the code below - handleChange methos is used in form fields:

  1. starting i = 0
  2. with the first change
  3. i should get updated with i+1
  4. and console.log(i) = should be 1, but get 0
  • I tried to research the lifecycles and read a lot of posts, but couldn't understand how to fix it (tried to simplify the question).

Thanks

const [i, setI] = useState(0)

const handleChange = input => event => {
        setI(i + 1)
        console.log(i)
        }

<ChildFormComponent handleChange={handleChange}/>

Solution

  • The setI function is async. I is not updated synchronously but asynchronously. If you want to log the new value of i use the useEffect hook and add i as its dependency.

    React.useEffect(() => {
      console.log(i)
    }, [i])