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 :
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;