how to pause usestate counter value react hoooks

Solutions on MaxInterview for how to pause usestate counter value react hoooks by the best coders in the world

showing results for - "how to pause usestate counter value react hoooks"
Anika
27 Sep 2020
1import React, { useState, useEffect } from 'react';
2
3const Timer = () => {
4  const [seconds, setSeconds] = useState(0);
5  const [isActive, setIsActive] = useState(false);
6
7  function toggle() {
8    setIsActive(!isActive);
9  }
10
11  function reset() {
12    setSeconds(0);
13    setIsActive(false);
14  }
15
16  useEffect(() => {
17    let interval = null;
18    if (isActive) {
19      interval = setInterval(() => {
20        setSeconds(seconds => seconds + 1);
21      }, 1000);
22    } else if (!isActive && seconds !== 0) {
23      clearInterval(interval);
24    }
25    return () => clearInterval(interval);
26  }, [isActive, seconds]);
27
28  return (
29    <div className="app">
30      <div className="time">
31        {seconds}s
32      </div>
33      <div className="row">
34        <button className={`button button-primary button-primary-${isActive ? 'active' : 'inactive'}`} onClick={toggle}>
35          {isActive ? 'Pause' : 'Start'}
36        </button>
37        <button className="button" onClick={reset}>
38          Reset
39        </button>
40      </div>
41    </div>
42  );
43};
44
45export default Timer;
46