ReactJS: onClick gets executed when rendered or loaded without a click

Xavier Yuhan Liu
1 min readApr 28, 2024

Quite a simple way to solve this.

Photo by Pankaj Patel on Unsplash

While working on my group project, I found that onClick is executed without a click. After searching Google, I finally found out why.

The answer is quite simple. Please change your code from this

<button onClick={handleClick()}>Click Me!</button>

to this

<button onClick={() => handleClick()}>Click Me!</button>

The reason for this is simple. When the button is loaded, the onClick function will be evaluated. The function returned from onClick will be executed each time the button is clicked.

So, we need to wrap the function we hope to execute every click into another function, returning the wanted function.

I found the answer on StackOverFlow.

--

--

Computer Science Student/Guitarist and Songwriter/Creator/World Explorer, Trying to Make the World a Better Place 🌠