Install react-timer-hook
masterYou can install the package using either yarn or npm.
yarn add react-timer-hook
# OR
npm install --save react-timer-hookrepository·master·Indexed 20 days ago
https://github.com/amrlabib/react-timer-hookA collection of custom React hooks for managing timers, stopwatches, and current time logic. Version 4.0.6 includes useTimer for countdowns with expiry timestamps, useStopwatch for count-up tracking with optional offsets, useTime for displaying the current time with 12/24-hour format support, and useInterval for executing callbacks at specified intervals.
You can install the package using either yarn or npm.
yarn add react-timer-hook
# OR
npm install --save react-timer-hookThe useTime hook returns the current time. You can specify a format of '12-hour' to include an ampm value. Like the other hooks, you can adjust the interval for update frequency.
import { useTime } from 'react-timer-hook';
const {
milliseconds, seconds, minutes, hours, ampm
} = useTime({
format: '12-hour',
interval: 20
});The useTimer hook is used to create a countdown timer. It requires an expiryTimestamp (a Date object) to define when the timer should end. You can optionally provide an onExpire callback, an autoStart boolean, and an interval to control the update frequency.
Note on interval: The interval does not change the timer's speed, but it defines how often the hook recalculates values. If you need to display milliseconds accurately, set a smaller interval (e.g., 20 or 100).
import { useTimer } from 'react-timer-hook';
const {
days, hours, minutes, seconds, milliseconds,
isRunning, start, pause, resume, restart
} = useTimer({
expiryTimestamp: new Date(),
onExpire: () => console.log('Expired!'),
interval: 20
});The useStopwatch hook is used to create a stopwatch that counts up. It can be configured with an autoStart flag, an interval for update frequency, and an offsetTimestamp to start the stopwatch from a specific time offset rather than zero.
import { useStopwatch } from 'react-timer-hook';
const {
days, hours, minutes, seconds, milliseconds,
isRunning, start, pause, reset
} = useStopwatch({
autoStart: true,
interval: 20
});| key | Type | Required | Description |
|---|---|---|---|
expiryTimestamp | Date object | YES | Defines how long the timer will run |
autoStart | boolean | No | If true, timer starts automatically (default: true) |
interval | number | No | Frequency of value calculation in ms (default: 1000) |
onExpire | Function | No | Callback executed when the timer expires |
| key | Type | Description |
|---|---|---|
milliseconds | number | Milliseconds value |
seconds | number | Seconds value |
minutes | number | Minutes value |
hours | number | Hours value |
days | number | Days value |
totalSeconds | number | Total seconds remaining (not converted to H/M/D) |
totalMilliseconds | number | Total milliseconds remaining (not converted to S/M/H/D) |
isRunning | boolean | Indicates if timer is running |
pause | function | Pauses the timer |
start | function | Starts timer from original expiryTimestamp if it was paused |
resume | function | Resumes countdown from the last paused state |
restart | function | Restarts with a new expiryTimestamp. Accepts (newExpiryTimestamp: Date, autoStart: boolean). |
| key | Type | Required | Description |
|---|---|---|---|
format | string | No | If set to '12-hour', time will include am/pm |
interval | number | No | Frequency of value calculation in ms (default: 1000) |
| key | Type | Description |
|---|---|---|
milliseconds | number | Milliseconds value |
seconds | number | Seconds value |
minutes | number | Minutes value |
hours | number | Hours value |
ampm | string | am/pm value (only if format is '12-hour') |
| key | Type | Required | Description |
|---|---|---|---|
autoStart | boolean | No | If true, stopwatch starts automatically (default: true) |
offsetTimestamp | Date object | No | Defines initial offset (e.g., setting it to 5 mins in the future makes stopwatch start at 0:0:5:0) |
interval | number | No | Frequency of value calculation in ms (default: 1000) |
| key | Type | Description |
|---|---|---|
milliseconds | number | Milliseconds value |
seconds | number | Seconds value |
minutes | number | Minutes value |
hours | number | Hours value |
days | number | Days value |
totalSeconds | number | Total seconds elapsed (not converted to H/M/D) |
totalMilliseconds | number | Total milliseconds elapsed (not converted to S/M/H/D) |
isRunning | boolean | Indicates if stopwatch is running |
start | function | Starts or resumes the stopwatch |
pause | function | Pauses the stopwatch |
reset | function | Resets to 0:0:0:0. Accepts (offsetTimestamp: Date, autoStart: boolean) to reset with a specific offset. |
The useTime hook provides a way to track and display the current time. It automatically updates based on a specified interval.
By default, it updates every second (SECOND_INTERVAL) and returns an object containing formatted time strings (e.g., hours, minutes, seconds) based on the current time.
format: A string that determines the time format. Options are '12-hour' or undefined (which defaults to 24-hour format).interval: A number representing the update frequency in milliseconds. If not provided, it defaults to SECOND_INTERVAL (1000ms).import { useTime } from 'react-timer-hook';
// Example: Using 12-hour format with a custom 1-second interval
const { hours, minutes, seconds } = useTime({ format: '12-hour', interval: 1000 });The Time.getFormattedTimeFromMilliseconds static method returns a FormattedTimeFromMillisecondsType object.
If you pass the option format: '12-hour', the returned object will include an ampm field (either 'am' or 'pm') and the hours field will be converted to a 12-hour format (0-11).
import Time, { FormattedTimeFromMillisecondsType } from './path-to-Time';
const formatted = Time.getFormattedTimeFromMilliseconds(3661000, '12-hour');
// Returns: { milliseconds: 0, seconds: 1, minutes: 1, hours: 1, ampm: 'am' }The Time.getTimeFromMilliseconds static method converts a raw millisecond value into a structured object containing various time units.
If isCountDown is set to true (default), it uses Math.ceil for total seconds, which is useful for countdown timers where you want the timer to show the current second until it actually hits zero. If isCountDown is false, it uses Math.floor.
import Time, { TimeFromMillisecondsType } from './path-to-Time';
const timeParts: TimeFromMillisecondsType = Time.getTimeFromMilliseconds(5000, true);
// Returns: { totalMilliseconds: 5000, totalSeconds: 5, milliseconds: 0, seconds: 5, minutes: 0, hours: 0, days: 0 }The useStopwatch hook provides functionality to manage a stopwatch, including starting, pausing, resetting, and tracking the elapsed time. It returns an object containing time components (hours, minutes, seconds, etc.) and control methods.
When calling useStopwatch, you can provide an optional settings object:
autoStart (boolean, default: true): Determines if the stopwatch starts automatically upon initialization.offsetTimestamp (Date): An optional Date object to set an initial offset for the stopwatch.interval (number): The update interval in milliseconds. Defaults to SECOND_INTERVAL (1000ms).import useStopwatch from 'react-timer-hook';
const {
seconds,
minutes,
hours,
milliseconds,
start,
pause,
reset,
isRunning
} = useStopwatch({ autoStart: true });The Time class provides several static methods to calculate millisecond differences relative to the current time:
getMillisecondsFromExpiry(expiry: Date): Calculates the milliseconds remaining between now and a future Date. Returns 0 if the date has already passed.getMillisecondsFromPrevTime(prevTime: number): Calculates the milliseconds elapsed since a previous timestamp (in milliseconds). Returns 0 if the provided timestamp is in the future.getMillisecondsFromTimeNow(): Returns the current timestamp adjusted by the timezone offset.import Time from './path-to-Time';
// Distance to a future date
const remaining = Time.getMillisecondsFromExpiry(new Date('2025-12-31'));
// Elapsed time since a previous timestamp
const elapsed = Time.getMillisecondsFromPrevTime(Date.now() - 5000);