Why a function in react is getting called three times when I am calling only one time
const NewApp = (props) => {
const [ counter, setCounter ] = useState(0)
const incrementCounterByOne = () => setCounter(counter + 1)
const decrementCounterByOne = () => setCounter(counter - 1)
const setCounterToZero = () => setCounter(0)
return (
<div>
<Display counter={counter} />
<Button handleClick={incrementCounterByOne} text="Increment" />
<Button handleClick={decrementCounterByOne} text="Decrement" />
<Button handleClick={setCounterToZero} text="Reset" />
{/* <button onClick={incrementCounterByOne}>Increment</button>
<button onClick={decrementCounterByOne}>Decrement</button>
<button onClick={setCounterToZero}>Reset</button> */}
</div>
)
}
const Button = (props) => {
console.log("clicked")
return (
<button onClick={props.handleClick}>
{props.text}
</button>
)
}
I am a newbie in react. When I am clicking on any button the button function is getting called three times but I am only clicking on one button at a time. I am a little confused on why so. If anyone can explain the process of how this is happening it be very helpful thank you!
Your console.log("clicked")
runs when a Button is called:
const Button = (props) => {
console.log("clicked")
and you have three buttons, so you see three logs whenever there's a re-render.
If you wanted to log only when a click occurs (and only log once, not three times), log inside the click handler instead.
<button onClick={(e) => {
console.log('clicked');
return props.handleClick(e);
}}>