`useInterval` delay of `null` with `immediate` still runs function
I have a situation where I want to run a useInterval function immediately when rendering the hook, but not when its delay is null.
const shouldRun = false;
useInterval(
() => {
// without this, func will run once because of `immediate`, as of v6.0.0
if (!shouldRun) return;
// ...
},
shouldRun ? 50 : null,
// need func to run immediately (not after 50 ms), but only if shouldRun is true
{ immediate: true },
);
As it currently works, immediate will make the func run once even when delay is null. I guess a user could want it this way, but in my opinion, this is unexpected behavior.
It's not a big deal since I can just check shouldRun at the top of the function and early exit, but I'd still bet that most people would be caught off guard by this.
Related: https://github.com/childrentime/reactuse/discussions/129
A side note, the controls option could be better documented as "Whether to control interval manually with returned start/stop functions instead of provided delay".
why not you just passed {immediate: false} if you dont yearn to run immediately?
I assume you mean passing { immediate: shouldRun }? In my opinion, that is basically the same as if (!shouldRun) return;, a hack/workaround for unexpected behavior. I think if the delay parameter is meant to be the on/off switch, it should work in all cases, and should also be the only on/off switch (not require you to press multiple off switches at a time).
But ultimately this is somewhat subjective. If you want to keep it as is, that's fine. But I strongly suspect more users will eventually get confused by this behavior.
Looking at the code, changing the behavior should be easy. But I suppose it would be a breaking change, as well.
@vincerubinetti You make a point. But the parameter immediate conduct the timer running also make sense at some aspects. And it affirmatively be a breaking change. So it's intractable.