title: How to create a stopwatch in React using useReducer hook and setInterval?
body: <p>I am trying to figure out how to implement useReducer in my stopwatch app that I made a while ago that uses setState. I am having lots of trouble implementing it, and I feel like my confusion centers around how the reducer function actually works.</p>
  <p>The major problem that I am having is that I am not sure how the reducer function actually works, as I am having trouble implementing the logic for the timer buttons. And I am assuming that I should be putting the logic in the switch statement.</p>
  <p>Here is my actual code:</p>
  <pre><code>import React, { useReducer } from &quot;react&quot;
  
  
  function init(initialState) {
    return { time: initialState }
  }
  
  let initialState = {
    timerOn: true,
    timerStart: 0,
    timerTime: 0
  };
  
  
  
  function reducer(state, action) {
    switch (action.type) {
      case 'start timer':
        return startTimer()
      case 'reset timer':
        return zerotimer(initialState)
      case 'resume timer':
        return
      default:
        return state
    }
  }
  
  
  function zerotimer(initialState) {
    return { initialState };
  }
  
  function startTimer(initialState) {
    this.timer = setInterval(() =&gt; {
      this.setState({
        timerTime: Date.now() - this.state.timerStart
      });
    }, 10);
  }
  
  function Timer({ initialState }) {
    const [state, dispatch] = useReducer(reducer, initialState)
    let centiseconds = (Math.floor(initialState / 10) % 100);
    let seconds = (Math.floor(initialState / 1000) % 60);
    let minutes = (Math.floor(initialState / 60000) % 60);
    let hours = (Math.floor(initialState / 3600000));
    return (
      &lt;div&gt;
        &lt;div&gt;
          &lt;div&gt;
            &lt;h2&gt;Time to run!&lt;/h2&gt;
          &lt;/div&gt;
          &lt;div&gt;Stopwatch&lt;/div&gt;
          &lt;div&gt;
            {hours} : {minutes} : {seconds} : {centiseconds}
          &lt;/div&gt;
          {state.timerOn === false &amp;&amp; state.timerTime === 0 &amp;&amp; (
            &lt;button onClick={() =&gt; dispatch({ type: 'start timer' })}&gt;Start&lt;/button&gt;
          )}
          {state.timerOn === true &amp;&amp; (
            &lt;button onClick={this.stopTimer}&gt;Stop&lt;/button&gt;
          )}
          {state.timerOn === false &amp;&amp; state.timerTime &gt; 0 &amp;&amp; (
            &lt;button onClick={this.startTimer}&gt;Resume&lt;/button&gt;
          )}
          {state.timerOn === false &amp;&amp; state.timerTime &gt; 0 &amp;&amp; (
            &lt;button onClick={() =&gt; dispatch({ type: 'reset timer' })}&gt;Reset&lt;/button&gt;
          )}
        &lt;/div&gt;
      &lt;/div&gt;
    )
  }
  
  export default Timer;
  
  </code></pre>