react hooks and setInterval

前端 未结 4 1387
孤独总比滥情好
孤独总比滥情好 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:18

    Because the current value is going to change on every "interval" as long as it should be running, then your code will start and stop a new timer on every render. You can see this in action here:

    https://codesandbox.io/s/03xkkyj19w

    You can change setInterval to be setTimeout and you will get the exact same behaviour. setTimeout is not a persistent clock, but it doesn't matter since they both get cleaned up anyways.

    If you do not want to start any timer at all, then put the condition before setInterval not inside of it.

      useEffect(
        () => {
          let id;
    
          if (run) {
            id = setInterval(() => {
              setValue(value + 1)
            }, 1000);
          }
    
          return () => {
            if (id) {
              alert(id) // notice this runs on every render and is different every time
              clearInterval(id);
            }
          };
        }
      );
    

提交回复
热议问题