Should useEffect
hook be used when it can be simplified using an event listener?
For example, in the below snippet code I use event listener to change some state and later useEffect
hook to react to that state change and do some other thing
import { useEffect, useState } from "react";
export default function Foo() {
const [isActive, setIsActive] = useState(true);
useEffect(() => {
// do any kind of business logic
}, [isActive]);
return (
<>
<button
type="button"
className="secondary"
onClick={() => setIsActive(true)}
>
ACTIVATE
</button>
<button
type="button"
className="secondary"
onClick={() => setIsActive(false)}
>
DEACTIVATE
</button>
</>
);
}
Should I move useEffect
logic to the onClick
listeners?
button
would cause it to fetch every click. Your question more depends what the the desired end result is! – AmbrosuseEffect
for simple operations I am just asking when is better to useuseEffect
orevent listeners
– Latt