I was experimenting with React 'ref' and was playing with below code snippet.
import { useEffect } from "react";
import { useRef } from "react";
import { useState } from "react";
const Button = () => {
const [counter, setCounter] = useState(0)
const btnRef = useRef();
useEffect(() => {
btnRef.current.addEventListener('click', function () {
console.log('counter ', counter);
setCounter(counter => 1);
})
})
return (
<button ref={btnRef}>Click Me</button>
)
}
export default Button;
What I couldn't understand is this code snippet is giving me 'counter' value twice in the console and with different values, every time I clicked on the button. Could someone help me in understanding what's happening here.
Why counter value is showing '0' again and again, when already its changed via setCounter function ?