복붙노트

[REACTJS] 후크와 반응에 카운트 다운 타이머를 구현

REACTJS

후크와 반응에 카운트 다운 타이머를 구현

해결법


  1. 1.

    const Timer = ({ seconds }) => {
      // initialize timeLeft with the seconds prop
      const [timeLeft, setTimeLeft] = useState(seconds);
    
      useEffect(() => {
        // exit early when we reach 0
        if (!timeLeft) return;
    
        // save intervalId to clear the interval when the
        // component re-renders
        const intervalId = setInterval(() => {
          setTimeLeft(timeLeft - 1);
        }, 1000);
    
        // clear interval on re-render to avoid memory leaks
        return () => clearInterval(intervalId);
        // add timeLeft as a dependency to re-rerun the effect
        // when we update it
      }, [timeLeft]);
    
      return (
        <div>
          <h1>{timeLeft}</h1>
        </div>
      );
    };
    
  2. from https://stackoverflow.com/questions/57137094/implementing-a-countdown-timer-in-react-with-hooks by cc-by-sa and MIT license