Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React click counter incrementing by 2

A little confused here: A simple click counter yet instead of incrementing by 1, it increments by 2.

function MyComponent() {
  const myComponentDiv = useRef(null)
  const [clickCount, setClickCount] = useState(0);


  const clickHandler = () => {
    setClickCount(clickCount +1)
  }
  useEffect(() => {
    myComponentDiv.current.addEventListener("click", clickHandler);
    return () => {
    myComponentDiv.current.removeEventListener("click", clickHandler);
    }
  }, [clickCount]);

  return (
    <div className="my-component" ref={myComponentDiv}>
      <h2 onClick={clickHandler}>
        My Component ({clickCount} clicks)
      </h2>
    </div>
  );
}
export default MyComponent;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You’re adding two click event listeners, one on the h2 and one on the div. If you click on the h2, the click bubbles/propagates up to trigger both. You should not be manually addEventListener with React, that’s what onClick is for.

You code should look like this:

function MyComponent() {
  const [clickCount, setClickCount] = useState(0);

  const clickHandler = () => {
    setClickCount((currentClickCount) => currentClickCount + 1);
  }

  return (
    <div className="my-component">
      <h2 onClick={clickHandler}>
        My Component ({clickCount} clicks)
      </h2>
    </div>
  );
}
export default MyComponent;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading