1

I'm curioused about the work of this code.
It's a simple code, I intended to raise counter for 1 and print on console.

but when I click the button the counter increases, also printing from 0 ~ to all the number that I increased.

run screenshot

Could you explain why this happens?

import { useState } from "react";

function App() {
  const [counter, setCounter] = useState(0);

  const onClick = () => {
    window.addEventListener("click", () => {
      console.log(counter);
    });
    setCounter((counter) => counter + 1);
  };

  return (
    <div className="App">
      <button onClick={() => onClick()}>Add & Print!</button>
      <div>{counter}</div>
    </div>
  );
}

export default App;
Chanmin
  • 13
  • 1
  • 5

2 Answers2

0

On every click you are adding an event listener. So on first click there is one event listener, on second 2, on third three and so on. (on nth click, n event listeners are there on window object).

There is also the situation of the event listener using stale state. The window event listener has closed over(closures) the old value of state and is logging it. So the first event listener is always using count = 0. The third event listener is using count = 2. So, on.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
0

You added onClick event to button tag and when the function is executed, onClick event to window is added. So whenever clicking button tag, addEventListener that order to add shows console.log is made. On the code, showing console.log doesn't need addEventListener because button tag already has onClick event.

In <button onClick={() => onClick()}>Add & Print!</button> tag, onClick event is executed whenever the tag is clicked,

Below,

    window.addEventListener("click", () => {
      console.log(counter);
    });

addEventListener adds event.

So whenever clicking button tag, addEventListener is executed(that adds events).

import { useState } from "react";

function App() {
  const [counter, setCounter] = useState(0);

  const onClick = () => {
// doesn't need window.addEventListener
//    window.addEventListener("click", () => {
      console.log(counter);
//    });
    setCounter((counter) => counter + 1);
  };

  return (
    <div className="App">
      <button onClick={() => onClick()}>Add & Print!</button>
      <div>{counter}</div>
    </div>
  );
}

export default App;
jacobkim
  • 1,043
  • 10
  • 20