Why is my function being called twice in React?
Prevent calling twice by using e.preventDefault()
.
changeShipping(e){
e.preventDefault();
console.log('clicked');
}
The problem is html related, rather than React related. By default clicking a label will also trigger the onClick event of the input element it is associated with. In your case the onClick event is attached to both the label and the input. So by clicking on the label, the event is fired twice: once for the label and once for the input associated with it.
Edit: Attaching the onClick listener to the input is a possible solution to the problem
e.stopPropagation()
is also worth exploring. I was handling an onMouseDown event, and preventDefault was not preventing multiple calls.
https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
Its because your app
component is a wrap in StrictMode
.
<React.StrictMode>
<App />
</React.StrictMode>,
If you are using
create-react-app
then it is found inindex.js
It is expected that setState
updaters will run twice in strict mode
in development. This helps ensure the code doesn't rely on them running a single time (which wouldn't be the case if an async render was aborted and later restarted). If your setState
updaters are pure functions (as they should be) then this shouldn't affect the logic of your application.
https://github.com/facebook/react/issues/12856#issuecomment-390206425