import {useState} from 'react';
const Counter = () =>{
let [counter,setCounter] = useState(0);
return(
<div className='counter-box'>
<span>{counter}</span>
<button onClick={setCounter(counter++)}></button>
</div>
)
}
export default Counter;
I'm using functional component here. Can someone tell me what's wrong with my code?
Yes.
Here the onClick
function is getting executed when it's rendered instead of user click event.
Solution 1:
import {useState} from 'react';
const Counter = () =>{
let [counter,setCounter] = useState(0);
return(
<div className='counter-box'>
<span>{counter}</span>
<button onClick={e => setCounter(counter+1)}></button>
</div>
)
}
export default Counter;
Instead of executing the code, we pass a function reference(anonymous arrow function) to the onClick
event.