react hooks and setInterval

前端 未结 4 1450
孤独总比滥情好
孤独总比滥情好 2021-02-06 08:14

Is there any alternative to just keeping a \"clock\" in the background to implement auto-next (after a few seconds) in carousel using react hooks?

The custom react hook

4条回答
  •  轮回少年
    2021-02-06 08:30

    So far, it seems that both solutions below work as desired:

    Conditionally creating timer — it requires that useEffect is dependent both on auto and current to work

    useEffect(
        () => {
          if (!auto) return;
          const interval = setInterval(_ => {
            next();
          }, autoInterval);
          return _ => clearInterval(interval);
        },
        [auto, current]
      );
    

    Conditionally executing update to state — it does not require useEffect dependencies

    useEffect(() => {
        const interval = setInterval(_ => {
          if (auto) {
            next();
          } else {
            // do nothing
          }
        }, autoInterval);
        return _ => clearInterval(interval);
      });
    

    Both solutions work if we replace setInterval by setTimeout

提交回复
热议问题