react-timer-hook

repository·master·Indexed 20 days ago

https://github.com/amrlabib/react-timer-hook

A 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.

Tokens
4K
Snippets
14
Records
20
Agent score
66%

What's inside react-timer-hook

  1. Use the useTime hook for current time

    master

    The 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 
    });
  2. Use the useTimer hook for countdown timers

    master

    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 
    });
  3. Use the useStopwatch hook for count-up timers

    master

    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 
    });
  4. useTimer Settings and Values

    master

    Settings

    keyTypeRequiredDescription
    expiryTimestampDate objectYESDefines how long the timer will run
    autoStartbooleanNoIf true, timer starts automatically (default: true)
    intervalnumberNoFrequency of value calculation in ms (default: 1000)
    onExpireFunctionNoCallback executed when the timer expires

    Values

    keyTypeDescription
    millisecondsnumberMilliseconds value
    secondsnumberSeconds value
    minutesnumberMinutes value
    hoursnumberHours value
    daysnumberDays value
    totalSecondsnumberTotal seconds remaining (not converted to H/M/D)
    totalMillisecondsnumberTotal milliseconds remaining (not converted to S/M/H/D)
    isRunningbooleanIndicates if timer is running
    pausefunctionPauses the timer
    startfunctionStarts timer from original expiryTimestamp if it was paused
    resumefunctionResumes countdown from the last paused state
    restartfunctionRestarts with a new expiryTimestamp. Accepts (newExpiryTimestamp: Date, autoStart: boolean).
  5. useTime Settings and Values

    master

    Settings

    keyTypeRequiredDescription
    formatstringNoIf set to '12-hour', time will include am/pm
    intervalnumberNoFrequency of value calculation in ms (default: 1000)

    Values

    keyTypeDescription
    millisecondsnumberMilliseconds value
    secondsnumberSeconds value
    minutesnumberMinutes value
    hoursnumberHours value
    ampmstringam/pm value (only if format is '12-hour')
  6. useStopwatch Settings and Values

    master

    Settings

    keyTypeRequiredDescription
    autoStartbooleanNoIf true, stopwatch starts automatically (default: true)
    offsetTimestampDate objectNoDefines initial offset (e.g., setting it to 5 mins in the future makes stopwatch start at 0:0:5:0)
    intervalnumberNoFrequency of value calculation in ms (default: 1000)

    Values

    keyTypeDescription
    millisecondsnumberMilliseconds value
    secondsnumberSeconds value
    minutesnumberMinutes value
    hoursnumberHours value
    daysnumberDays value
    totalSecondsnumberTotal seconds elapsed (not converted to H/M/D)
    totalMillisecondsnumberTotal milliseconds elapsed (not converted to S/M/H/D)
    isRunningbooleanIndicates if stopwatch is running
    startfunctionStarts or resumes the stopwatch
    pausefunctionPauses the stopwatch
    resetfunctionResets to 0:0:0:0. Accepts (offsetTimestamp: Date, autoStart: boolean) to reset with a specific offset.
  7. Use the useTime hook to display current time

    master

    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.

    Settings

    • 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 });
  8. Get formatted time with 12-hour support using Time.getFormattedTimeFromMilliseconds()

    master

    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' }
  9. Convert milliseconds to time components with Time.getTimeFromMilliseconds()

    master

    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 }
  10. Use the useStopwatch hook

    master

    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.

    Settings

    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 });
  11. Calculate millisecond offsets with Time utility methods

    master

    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);