"use client"
import React, { useEffect } from 'react'
import { useState } from 'react';
export default function page() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount((count)=>count + 1);
};
function checkVal(){
console.log(count)
}
useEffect(()=>{
setInterval(checkVal,1000)
}
,[])
return (
<div>
<button onClick={handleClick}>{count}</button>
<button onClick={checkVal}>clickmetocheck</button>
</div>
)
}
I have a following code which checks the value of count when
- checkVal is called through setInterval
- checkVal is called through onClick event
Since these two condition is calling the same function checkVal(), I was expecting console to print the same number. However, checkVal through setInterval was only printing the default value even when the value was updated through handleClick(). And checkVal through onclick event was correctly printing out count.
Same code, different behaviour. Why does this happen?
1