I'm trying to do a simple setState on a button with a counter and apply different background color depending on its state. It runs perfectly for the first 3 button clicks and on the fourth one and so on it does this: counter log
Here's the code:
useEffect(() => {
const changePower = () => {
if (power === 'on') {
document.getElementById('btn-trigger').style.backgroundColor = "red";
setPower('off');
} else if (power==='off') {
document.getElementById('btn-trigger').style.backgroundColor = "lime";
setPower('on');
}
setCount(count + 1);
}
document.getElementById('btn-trigger').addEventListener('click', changePower);
console.log(count);
}, [power])
Any help would be awesome, Thank You!
If you set Power in the useEffect, it will trigger itself.
useEffect(() => {
if(count%2)
document.getElementById('btn-trigger').style.backgroundColor = "red";
else
document.getElementById('btn-trigger').style.backgroundColor = "lime";
}, [count])
const handeClick = () => {
setCount(count + 1);
}
you are setting "power" value by "setPower" inside a useEffect who is listening to changes on "power".
You need to clean up the events:
useEffect(() => {
const changePower = () => {
if (power === 'on') {
document.getElementById('btn-trigger').style.backgroundColor = "red";
setPower('off');
} else if (power==='off') {
document.getElementById('btn-trigger').style.backgroundColor = "lime";
setPower('on');
}
setCount(count + 1);
}
document.getElementById('btn-trigger').addEventListener('click', changePower);
console.log(count);
return () => window.removeEventListener("click", changePower) <-----
}, [power])
In addition: the changePower function should be declared outside of the useEffect hook. You use the useCallback hook here.