Menggunakan waktu yang terselap

const Clock = ({ dispatch, inProgress, ticksElapsed }) => {
  React.useEffect(() => {
    const progressTimer = setInterval(function () {
      inProgress && dispatch({ type: 'CLOCK_RUN' });
    }, 500);
    return () =>
      //inprogress is stale so when it WAS true
      //  it must now be false for the cleanup to
      //  be called
      inProgress && clearInterval(progressTimer);
  }, [dispatch, inProgress]);

  return <h1>{ticksElapsed}</h1>;
};

const App = () => {
  const [inProgress, setInProgress] = React.useState(false);
  const [ticksElapsed, setTicksElapsed] = React.useState(0);
  const dispatch = React.useCallback(
    () => setTicksElapsed((t) => t + 1),
    []
  );
  return (
    <div>
      <button onClick={() => setInProgress((p) => !p)}>
        {inProgress ? 'stop' : 'start'}
      </button>
      <Clock
        inProgress={inProgress}
        dispatch={dispatch}
        ticksElapsed={ticksElapsed}
      />
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById('root'));
Different Dove