0

I am trying to code a countdown clock and the "mins" is from a brother component. If I take off setMin from useEffect then it is not changing while the value change in source components, but if I leave it in useEffect it will re-rendering every time if the seconds change and makes it immutable. Anyway, can I fix this problem? If I need useRef how can I use it with setMin?

export default function Timer(props) {
  const { count } = props;
  const [isPlay, setIsPlay] = useState(false);
  const [isRestore, setIsRestore] = useState(false);
  const [second, setSecond] = useState(0);
  const [isBreak, setIsBreak] = useState(false);
  const [min, setMin] = useState(count)

  useEffect(() => {
    setMin(count)
    let alarm = document.getElementById("beep");
    const countdown = () => {
      setTimeout(() => {
        if (second === 0 && min > 0) {
          setMin(min-1);
          setSecond(59);
        } else if (min >= 0 && second > 0) {
          setSecond(second - 1);
        } else {
          alarm.play();
          alarm.addEventListener("ended", () => {
            setIsBreak(!isBreak);
          });
        }
      }, 1000);
    };
    if (isPlay) {
      countdown();
    } else {
      alarm.pause();
    }

    if (isRestore) {
      setIsPlay(false);
      alarm.currentTime = 0;
      setIsRestore(false);
    }
  },[isPlay, isRestore, second, isBreak,min,count]);
Sean Lau
  • 43
  • 3

1 Answers1

0

I think the majority of your logic should be outside of the useEffect hook. Take a look at this answer Countdown timer in React, it accomplishes pretty much the same task as yours and should help you get an idea of the necessary logic

Nathan
  • 56
  • 8
  • Hi Nathan, Thank you for your quick response. I moved my logic outside of the useEffect Hook, but the minutes still not changing if I increment the count from another component. if I log count in console it is increment as normal but ```const [min, setMin] = useState(count)``` not change the min value unless I put ```setMin(count)``` inside useEffect but I will over-write the minutes of countdown function – Sean Lau Jul 16 '22 at 07:08