0

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 ?

user3760959
  • 457
  • 1
  • 6
  • 18

1 Answers1

1

when you don't pass a dependency array, useEffect is triggered on every render including the first. So it renders for the first time, then you call setCounter, which triggers render the second time. You probably looking for this;

 useEffect(() => {
        btnRef.current.addEventListener('click', function () {
            console.log('counter ', counter);
            setCounter(counter => 1);
        })
    },[]) // <-- this is an empty dependency array
ilkerkaran
  • 4,214
  • 3
  • 27
  • 42
  • Thanks. I passed the empty [] as dependency, now console is showing only one value. But it's not updating the state, counter state is not getting set to '1'. On every click, counter value shows as '0'. – user3760959 Jul 22 '21 at 16:24