{"id":11883,"library":"react-timer-hook","title":"React Timer Hook","description":"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.","status":"active","version":"4.0.5","language":"javascript","source_language":"en","source_url":"https://github.com/amrlabib/react-timer-hook","tags":["javascript","react","react-hook","react-hooks","timer","countdown","time","clock","useTimer","typescript"],"install":[{"cmd":"npm install react-timer-hook","lang":"bash","label":"npm"},{"cmd":"yarn add react-timer-hook","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-timer-hook","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Runtime dependency for all React hooks, specifically requires React >=16.8.0 for Hooks API.","package":"react","optional":false}],"imports":[{"note":"The `useTimer` hook is a named export. Using a default import will lead to a runtime error or a TypeScript compilation error.","wrong":"import useTimer from 'react-timer-hook';","symbol":"useTimer","correct":"import { useTimer } from 'react-timer-hook';"},{"note":"While some bundlers might transpile CommonJS `require` to work with ES Modules, `react-timer-hook` is primarily designed for modern ES Module `import` syntax. For TypeScript users, `import` is required.","wrong":"const { useStopwatch } = require('react-timer-hook');","symbol":"useStopwatch","correct":"import { useStopwatch } from 'react-timer-hook';"},{"note":"React hooks conventionally start with `use` and follow camelCase naming. Ensure correct casing when importing.","wrong":"import { UseTime } from 'react-timer-hook';","symbol":"useTime","correct":"import { useTime } from 'react-timer-hook';"},{"note":"For TypeScript projects, `TimerControls` is an interface describing the return values and control functions of `useTimer`. It should be imported as a type using `import type`.","symbol":"TimerControls","correct":"import type { TimerControls } from 'react-timer-hook';"}],"quickstart":{"code":"import React from 'react';\nimport { useTimer } from 'react-timer-hook';\n\ninterface MyTimerProps {\n  expiryTimestamp: Date;\n}\n\nfunction MyTimer({ expiryTimestamp }: MyTimerProps) {\n  const {\n    totalSeconds,\n    milliseconds,\n    seconds,\n    minutes,\n    hours,\n    days,\n    isRunning,\n    start,\n    pause,\n    resume,\n    restart,\n  } = useTimer({ expiryTimestamp, onExpire: () => console.warn('onExpire called'), interval: 20 });\n\n  return (\n    <div style={{textAlign: 'center'}}>\n      <h1>react-timer-hook </h1>\n      <p>Timer Demo</p>\n      <div style={{fontSize: '100px'}}>\n        <span>{days}</span>:<span>{hours}</span>:<span>{minutes}</span>:<span>{seconds}</span>:<span>{milliseconds}</span>\n      </div>\n      <p>{isRunning ? 'Running' : 'Not running'}</p>\n      <button onClick={start}>Start</button>\n      <button onClick={pause}>Pause</button>\n      <button onClick={resume}>Resume</button>\n      <button onClick={() => {\n        const time = new Date();\n        time.setSeconds(time.getSeconds() + 300); // Set for 5 minutes from now\n        restart(time);\n      }}>Restart 5min</button>\n    </div>\n  );\n}\n\nexport default function App() {\n  const time = new Date();\n  time.setSeconds(time.getSeconds() + 600); // 10 minutes timer\n  return (\n    <div>\n      <MyTimer expiryTimestamp={time} />\n    </div>\n  );\n}\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Review timer display logic for the new `milliseconds` output. If higher precision is required, set the `interval` option to a smaller value (e.g., 20ms or 100ms) when initializing the hook.","message":"Version 4.0.0 introduced support for milliseconds in the `useTimer` and `useStopwatch` hooks. While not strictly a breaking API change for existing users, applications relying solely on `seconds` as the smallest unit might need to adjust their display logic or `interval` setting if they intend to leverage or avoid millisecond precision.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Upgrade to `react-timer-hook@4.0.2` or a later version to ensure all type definitions are correctly bundled and available for TypeScript projects.","message":"Prior to v4.0.2, TypeScript definition files were not consistently included in the distributed package. This caused compilation errors for TypeScript users attempting to import and use the library's hooks and types.","severity":"gotcha","affected_versions":"<4.0.2"},{"fix":"Update `react-timer-hook` to version `3.0.4` or later. This version includes a critical fix that improves the accuracy of `useStopwatch` even when the browser tab is not active.","message":"Older versions of `useStopwatch` (prior to v3.0.4) experienced inaccuracies in timing when the browser tab was inactive. This was due to browser throttling of `setTimeout` and `setInterval` in background tabs, leading to incorrect stopwatch readings upon returning to the tab.","severity":"gotcha","affected_versions":"<3.0.4"},{"fix":"Always ensure that `expiryTimestamp` is initialized with a valid `Date` object, such as `new Date(Date.now() + 60 * 1000)` for a timer set one minute in the future.","message":"The `expiryTimestamp` prop for `useTimer` is mandatory and must be a valid `Date` object representing a future point in time. Providing an invalid or `undefined` value will cause the timer to behave unexpectedly or throw runtime errors.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `expiryTimestamp` is always a valid `Date` object initialized with a future time, e.g., `new Date(Date.now() + 5 * 60 * 1000)` for a 5-minute timer.","cause":"This error typically occurs when the `expiryTimestamp` prop passed to `useTimer` is `undefined` or not a valid `Date` object, leading to failed attempts to call Date methods.","error":"TypeError: Cannot read properties of undefined (reading 'setSeconds') at MyTimer"},{"fix":"Verify that you are using named imports (`import { useTimer } from 'react-timer-hook';`). If the issue persists, ensure `react-timer-hook@4.0.2` or newer is installed and your `tsconfig.json` correctly includes `node_modules/@types`.","cause":"This TypeScript error indicates that type definitions are not being recognized, or you're attempting to use a default import instead of a named import for `useTimer`.","error":"Property 'useTimer' does not exist on type 'typeof import(\"react-timer-hook\")'."},{"fix":"Upgrade your `react-timer-hook` package to version `3.0.4` or higher. This version contains the necessary fix for improved accuracy in inactive browser tabs.","cause":"This was a known bug in `react-timer-hook` versions older than `3.0.4`, especially for `useStopwatch`, where browser throttling of background tabs affected timer precision.","error":"Timer is not accurate or stops when browser tab is inactive."},{"fix":"Adopt the ES Module import syntax: `import { useTimer } from 'react-timer-hook';`. If you are strictly in a CommonJS environment, confirm your transpilation setup (e.g., Babel, Webpack) is correctly configured for ES module interop.","cause":"This error usually arises from attempting to `require` an ES Module named export in a CommonJS environment, or incorrect module resolution setup in your build pipeline.","error":"SyntaxError: Named export 'useTimer' not found. The requested module 'react-timer-hook' does not provide an export named 'useTimer'"}],"ecosystem":"npm"}