function LoginComponent(){
const [clicked, setClicked] = useState(false)
function handleClick(){
console.log('before', clicked)
setClicked(true)
console.log('after', clicked)
}
return(
<a onClick={handleClick}>
random text
</a>
)
}
When I run this, the console outputs before false after false. Why is this? I have no clue why this behavior is like this.
Because setting state is an asynchronous action. It takes some time to update. Check react documentation link to know more
You can check the updated value by
useEffect(()=> {
console.log("clicked", clicked);
},[clicked]);
There are couple of reasons for this behavior:
If you want to log the updated value of clicked, put the log statement in the useEffect hook.
You can't update and log the updated value of any state variable in the same render. Component will have to re-render to reflect changes due to state update.
Similarly, if you want to call a function with the updated value of clicked, call the function from inside the useEffect hook.
setClicked is asynchronous. You must check the state updated in useEffect
function LoginComponent(){
const [clicked, setClicked] = useState(false)
function handleClick(){
setClicked(true)
}
useEffect(() => {
console.log(clicked);
},[clicked])
return(
<a onClick={handleClick}>
random text
</a>
)
}