React Timer Hook

4.0.5 · active · verified Sun Apr 19

react-timer-hook is a robust custom React hook library designed to simplify the implementation of timers, stopwatches, and general time-based logic within React components. It provides three core hooks: `useTimer` for countdowns, `useStopwatch` for count-up timers, and `useTime` for retrieving the current time. Currently stable at version `4.0.5`, the library maintains an active release cadence, frequently addressing bug fixes, dependency updates, and minor feature enhancements. A key differentiator is its out-of-the-box TypeScript support and its intelligent handling of browser tab inactivity to ensure accurate timer behavior, especially for stopwatches. It exposes a comprehensive set of time values including days, hours, minutes, seconds, milliseconds, and total raw seconds/milliseconds, along with functions for starting, pausing, resuming, and restarting timers, offering fine-grained control for various time-sensitive UI/UX requirements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a countdown timer using `useTimer`, showcasing its display of days, hours, minutes, seconds, and milliseconds, along with controls for starting, pausing, resuming, and restarting the timer. It also includes an `onExpire` callback.

import React from 'react';
import { useTimer } from 'react-timer-hook';

interface MyTimerProps {
  expiryTimestamp: Date;
}

function MyTimer({ expiryTimestamp }: MyTimerProps) {
  const {
    totalSeconds,
    milliseconds,
    seconds,
    minutes,
    hours,
    days,
    isRunning,
    start,
    pause,
    resume,
    restart,
  } = useTimer({ expiryTimestamp, onExpire: () => console.warn('onExpire called'), interval: 20 });

  return (
    <div style={{textAlign: 'center'}}>
      <h1>react-timer-hook </h1>
      <p>Timer Demo</p>
      <div style={{fontSize: '100px'}}>
        <span>{days}</span>:<span>{hours}</span>:<span>{minutes}</span>:<span>{seconds}</span>:<span>{milliseconds}</span>
      </div>
      <p>{isRunning ? 'Running' : 'Not running'}</p>
      <button onClick={start}>Start</button>
      <button onClick={pause}>Pause</button>
      <button onClick={resume}>Resume</button>
      <button onClick={() => {
        const time = new Date();
        time.setSeconds(time.getSeconds() + 300); // Set for 5 minutes from now
        restart(time);
      }}>Restart 5min</button>
    </div>
  );
}

export default function App() {
  const time = new Date();
  time.setSeconds(time.getSeconds() + 600); // 10 minutes timer
  return (
    <div>
      <MyTimer expiryTimestamp={time} />
    </div>
  );
}

view raw JSON →