I am new to react and react hooks. I am creating a custom react hook. Why is useState not working as expected.
import { useEffect, useState } from 'react'
export const useMyHook = () => {
const [myVal, setVal] = useState(0) //myVal is 0
useEffect(() => {
initialize()
},[])
const initialize = () => {
setVal(100)
console.log(myVal) // displays 0, not 100 as I expect
}
return myVal
}
// In my component I call it as follows
import { useMyHook } from 'useMyHook'
...
const myHook = useMyHook()
2
Answers
I think you misunderstand the
useState
here.First, when the component using the
useMyHook
is mounted, theuseEffect
runs as part of the initial render, and it calls the initialize function due to the[]
dependency.Then, inside the
initialize
function, you callsetVal(100)
to update the value of myVal. However, the update is asynchronous, meaning that the new value won’t be available immediately. At this point, themyVal
state variable still holds its old value of 0 because the state update is not yet completedIf you want to log the latest
myVal
value you can useuseEffect
like thisTo see the updated value of myVal, you can use the useEffect hook with a dependency on myVal. When the value of myVal changes, the effect will run, and you can log the updated value.