reactuse icon indicating copy to clipboard operation
reactuse copied to clipboard

`useInterval` delay of `null` with `immediate` still runs function

Open vincerubinetti opened this issue 10 months ago • 3 comments

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".

vincerubinetti avatar Mar 12 '25 02:03 vincerubinetti

why not you just passed {immediate: false} if you dont yearn to run immediately?

childrentime avatar Mar 12 '25 03:03 childrentime

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 avatar Mar 12 '25 18:03 vincerubinetti

@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.

childrentime avatar May 23 '25 06:05 childrentime