React's useEffect
looks like this:
useEffect(() => {
effect
return () => {
cleanup
}
}, [input])
where input
is a list of values that trigger the effect when changed.
Let's say that I'm watching a number and I only want to trigger the effect when the number reaches 10. Is it possible to do that?
So far the best I could come up with is to encode the watched expression in a boolean value. The effect is then triggered twice, once when the boolean flips from false to true and a second time when it flips back to false. This is once too many.
Here's a small example:
export default function App() {
const [num, setNum] = useState(0);
const hit10 = num === 10;
useEffect(() => {
console.log("resetting");
setNum(0);
}, [hit10]);
return (
<button
onClick={() => {
setNum(num + 1);
}}
>
{num}
</button>
);
}