Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-timing-hooks

EricLambrecht6.7kMIT5.1.1TypeScript support: included

React hooks for setTimeout, setInterval, requestAnimationFrame, requestIdleCallback

react, interval, timeout, effect, loop, throttle, animation, frame, requestAnimationFrame, idle, callback, hook, rendering, rate-limiting, clock, timer, debounce, time, timing, setInterval

readme

logo

npm minified types checks Coverage Status

What's this?!

This is a very little package with React hooks wrapping time-related vanilla Javascript functions, so you can use them with minimal effort in your React apps without having to worry about manual clean up, or writing boilerplate to pause/resume intervals etc.

Feature Overview

  • Hooks for all timing-related vanilla JS functions like:
  • …and additional utility hooks for common tasks like
    • throttling: useThrottledState(), useThrottle(), useDebounce()
    • GFX/animation/rendering: useAnimationFrameLoop()
    • reactive counters: useCounter(), useCountdown(), useTimer()
    • time: useClock()
    • async effects: useTimeoutEffect(), useIdleCallbackEffect()
    • oscillation: useOscillator()
  • Reactive intervals: intervals can be controlled via pause, resume, start or stop
  • A versatile API: customizable settings, many hook "flavors" depending on the use-case.
  • Automatic clean-ups of pending timers, intervals etc. on unmount
  • Callbacks are automatically memoized
  • Full Typescript support
  • Very lightweight (no transitive dependencies!)
  • Tree-shakable — You only bundle what you use!

Installation

# via npm
npm i react-timing-hooks

# via yarn
yarn add react-timing-hooks

Documentation

https://ericlambrecht.github.io/react-timing-hooks/

How to migrate

https://ericlambrecht.github.io/react-timing-hooks/migrations/

Some Examples

A "status logger" with useInterval()

`jsx harmony import { useInterval } from 'react-timing-hooks'

const StatusLogger = () => { const logUpdates = () => console.log('status update') // could also be intialized with { startOnMount: true } to immediately start the interval const { start, pause, resume, isPaused } = useInterval(logUpdates, 1000)

return

<button onClick={start}>Do stuff</button> <button onClick={isPaused ? resume : pause}>Toggle Status Updates</button>
}

----

#### Throttle a button click with `useThrottle()`

```jsx harmony
import { useThrottle } from 'react-timing-hooks'

const HelloWorld = () => {
  const [result, setResult] = useState(null)
  const updateResult = () => setResult(extremeMegaCalculation())

  const onButtonClick = useThrottle(updateResult, 1000)

  return <div>
    <button onClick={onButtonClick}>Spam me!</button>
    <p>Result: {result}</p>
  </div>
}

Display the user's browsing time using useTimer()

`jsx harmony import { useTimer } from 'react-timing-hooks'

const BrowsingTime = () => { const [elapsedSeconds] = useTimer(0, { startOnMount: true }) return You've been browsing this page for {elapsedSeconds} seconds. }

----

#### Display the current time with `useClock()`
```jsx harmony
import { useTimeout } from 'react-timing-hooks'

const Clock = () => {
  // This will show a time like 1:13:56 PM (supports localized formats as well).
  // The displayed time will update every second
  const [currentTime] = useClock()
  return <span>{currentTime}</span>
}

A canvas renderer using useAnimationFrameLoop()

`jsx harmony import { useAnimationFrameLoop } from 'react-timing-hooks'

const Renderer = () => { const delta = useRef(0) const canvasRef = useRef(null) const canvas = canvasRef.current const context = canvas.getContext('2d')

const updateCanvas = (d) => { context.fillStyle = '#000000' context.fillRect(d, d, context.canvas.width, context.canvas.height) }

const { start, stop, isStopped } = useAnimationFrameLoop(() => { delta.current += 1 updateCanvas(delta.current) })

return <> <canvas ref={canvasRef} {...props}/> <button onClick={isStopped ? start : stop}> {isStopped ? "Start rendering" : "Stop rendering"} </button> </> }


## Why does this exist?

I was once working for a company where the project required lots of timeouts and such. I quickly noticed that 
writing a timeout or anything similar requires a lot of **boilerplate** (if you don't do it quick and dirty).
Dan Abramov showcased this in [one of his blogposts](https://overreacted.io/making-setinterval-declarative-with-react-hooks/) a while a go.

This library is supposed to give you easy access to those time-related functionalities while keeping your code clean and concise. 
You will **not** have to manually clean up timers or intervals.

Another common use-case is pausing/resuming or starting/stopping intervals (or loops). This lib offers
callbacks for that. So pausing is really just a matter of calling a `pause()` function for example.

Many frequent use cases also have their own utility hook, like `useThrottle`, `useCountdown` or `useAnimationFrameLoop`
to make things even easier.

Needless to say, every hook is already tested and typed (so you don't have to).

### Some "Before-/After-Code"

A simple interval that increments a counter on every second and can be manually started upon user input:

#### Before

```jsx harmony
import { useEffect, useState } from 'react'

const Counter = () => {
  const [counter, setCounter] = useState(0)
  const [startInterval, setStartInterval] = useState(false)
  const intervalId = useRef(null)

  useEffect(() => {
    if (startInterval) {
      intervalId.current = setInterval(() => setCounter(c => c + 1), 1000)
    }
  }, [startInterval])

  useEffect(() => {
    return function onUnmount() {
      if (intervalId.current !== null) {
        clearInterval(intervalId.current)
      }
    }
  }, [intervalId])

  return <>
    <button onClick={() => setStartInterval(true)}>Start counting</button>
    <p>{counter}</p>
  </>   
}

After

`jsx harmony import { useState } from 'react' import { useInterval } from 'react-timing-hooks'

const Counter = () => { const [counter, setCounter] = useState(0)

const { start } = useInterval(() => setCounter(c => c + 1), 1000)

return <> <button onClick={start}>Start counting</button>

{counter}

</> }


Well,… actually, there is even a shorter way using the utility hook `useTimer()` 🙈

#### After After

```jsx harmony
import { useCounter } from 'react-timing-hooks'

const Counter = () => {
  const [counter, { start }] = useTimer(0)

  return <>
    <button onClick={start}>Start counting</button>
    <p>{counter}</p>
  </>
}

Another example: You might have a timeout that runs under a certain condition. In this case a cleanup has to be done in a separate useEffect call that cleans everything up (but only on unmount).

Before

`jsx harmony import { useEffect } from 'react'

const TimeoutRenderer = ({ depA, depB }) => { const [output, setOutput] = useState(null) const timeoutId = useRef(null)

useEffect(() => { if (depA && depB) { timeoutId.current = setTimeout(() => setOutput('Hello World'), 1000) } }, [depA, depB])

useEffect(() => { return function onUnmount() { if (timeoutId.current !== null) { clearTimeout(timeoutId.current) } } }, [timeoutId])

return output ? (

{output}
) : null }


#### After

```jsx harmony
import { useState } from 'react'
import { useTimeoutEffect } from 'react-timing-hooks'

const TimeoutRenderer = ({ depA, depB }) => {
  const [output, setOutput] = useState(null)

  useTimeoutEffect((timeout, clearAll) => {
    if (depA && depB) {
      timeout(() => setOutput('Hello World'), 1000)
    }
    // you could even add more timeouts in this effect 
    // without any more boilerplate
  }, [depA, depB])

  return output ? (
    <div>{output}</div>
  ) : null
}

In this case react-timing-hooks automatically took care of cleaning up the timeout for you (if the component is mounted for less than a second for instance).

Memoization

You don't have to worry about memoization of your callbacks (by using useCallback) for example. React Timing Hooks is taking care of that for you. So even if you pass a simple inline arrow function to one of these hooks, the return value (if there is one) will not change on every render but instead stay the same (i.e. it will be memoized).

This means something like this is safe to do:

const [foo, setFoo] = useState(null)
const onFooChange = useTimeout(() => console.log('foo changed one second ago!'), 1000)

// the following effect will run only when "foo" changes, just as expected.
// "onFooChange" is memoized and safe to use in a dependency array.
useEffect(() => {
  onFooChange()
}, [foo, onFooChange])

Bundle Size

The whole lib is tree-shakable, i.e. only hooks you actually use end up in your bundle. So far, we also do not use any transitive dependencies. So don't worry about the bundle size.

But check for yourself: https://bundlephobia.com/result?p=react-timing-hooks

Contributing

see CONTRIBUTING.md

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

5.1.1 (2025-11-06)

Bug Fixes

  • Fix package breaking reference error in logError/logWarning functions (8abc434), closes #41

5.1.0 (2024-09-20)

Features

  • Add useOscillator() hook - Toggles a boolean on and off repeatedly (0b80200)
  • New option isLeading for the useInterval() hook (98a95db), closes #39

5.0.2 (2024-09-20)

Bug Fixes

5.0.1 (2024-08-03)

Bug Fixes

  • Fix npm package description (39aaffb)

5.0.0 (2024-08-02)

⚠ BREAKING CHANGES

  • Paused clocks will now keep running in the background by default
  • Counters will now reset on stop by default.

Features

  • Add reset function to counters, and option to reset on stop (b1c8ee9)
  • Add useThrottledState() hook to tame rapid firing state updates (f56261a), closes #35
  • Allow clock to keep running in background during pause (to resume at the right time) (8021bcd)

Bug Fixes

  • Fix some vulnerabilities using npm audit fix (1be9a7a)
  • Fix timers not resetting on stop (f19ef08), closes #36

4.0.1 (2022-12-18)

Bug Fixes

  • Add missing export for useThrottle() (609bc76)

4.0.0 (2022-12-18)

⚠ BREAKING CHANGES

  • timeout: useTimeout() will not implicitly debounce its callbacks anymore. A new hook useDebounce() was added to explicitly use this feature properly.
  • countdown: useCountdown() will now have a mandatory end param and will automatically stop and fire an event when this value is reached.
  • clock: The return value of useClock() is now an array: [time, controls] (controls being pause/resume, start/stop etc.).
  • timer: The return value of useTimer() is now an array: [timerValue, controls] (controls being pause/resume, start/stop etc.)
  • interval: Intervals won't start immediately on mount anymore. They will have to be started manually or explicitly be allowed to start on mount via options.startOnMount. This change affects useInterval, useCounter, useTimer and useCountdown.
  • animation-frame: The second argument (pause/stop) was removed from useAnimationFrameLoop() in favor of controls like they are used in useInterval(), useCounter() etc. By default, the hook also won't start to loop on mount anymore (though this is still available as an option).

Features

  • animation-frame: useAFL can now be controlled like useInterval(), also fixed unnecessary re-renders (24789a9), closes #33
  • clock: Add ability to "stop the clock". (1c10837)
  • countdown: Add end to useCountdown() and an event to listen to (2e5b6c9)
  • debounce: Add new hook useDebounce() (15aca52)
  • interval: Add option to start interval on mount (d791a94), closes #32
  • throttle: Add new hook useThrottle() for rate-limiting (224c15b)
  • timer: Add ability to control timer state (pause etc.) (b4ab3be), closes #34

3.2.1 (2022-12-14)

Bug Fixes

  • Add missing exports for useCounter and useCountdown (5e4b3c0)

3.2.0 (2022-12-14)

Features

  • countdown: Add new countdown hook. (fc4283b)
  • counter: Add counter hook. A more customizable version of useTimer(). (77ccea5)
  • interval: Allow pausing, resuming, stopping of intervals (a0e0c3f)

3.1.0 (2022-12-09)

Features

  • timeout: Allow manual clearance of timeouts (8a589b8), closes #28

3.0.0 (2022-12-09)

⚠ BREAKING CHANGES

Support for Node 10 and 12 was dropped (since they already reached EOL).

However, the API itself has no breaking changes, so it should be safe to update as long as you use Node 14 or higher!

Features

  • react: Add official support for React 18 (cf7114f)

ci

  • 🚀 Do not test Node 10 and 12 anymore, add tests for Node 18 (2f2a670)

2.2.3 (2022-02-19)

Bug Fixes

  • Fix infinite render loop in paused useAnimationFrameLoop (bda5715), closes #25

2.2.2 (2022-01-22)

Bug Fixes

  • Hot fix useClock API, unpublish 2.2.1, which was published a couple of minutes ago (64a5dcb)

2.2.1 (2022-01-22)

Bug Fixes

  • Fix useClock export, also change it's api while still possible (5ebc423)

2.2.0 (2022-01-19)

Add support for React 17.

Features

  • updated React dependency version requirement (9a4d6b1)

2.1.0 (2022-01-15)

Features

  • Add a new hook "useClock" that displays time (7e88d12), closes #17

2.0.0 (2020-09-24)

⚠ BREAKING CHANGES

  • Node 8 is no longer supported.

  • 🔧 Drop support for Node 8 (53e99b7)

1.4.2 (2020-09-24)

Warning: This build does not support Node 8 anymore. Please use version 2.0.0 instead.

Bug Fixes

  • Fix potential security issue in lodash (e9fe8fe)
  • Fix security issue in dot-prop by updating standard-version (c2fa24e)

1.4.1 (2020-07-25)

Bug Fixes

  • Fix timeouts not being properly unmounted (if more than 1) (df2d247), closes #4

1.4.0 (2020-06-12)

Features

  • Add second param to useTimeoutEffect callback to manually clean the timeout (428c3f7)

1.3.2 (2020-03-28)

Updated homepage in package.json and overhauled the documentation.

Technically identical to 1.3.1.

1.3.1 (2020-03-27)

Bug Fixes

  • Add missing docs for new hook "useTimer" (e7b30fd)

1.3.0 (2020-03-27)

Features

  • Add utility hook "useTimer" (1874244)

1.2.0 (2020-03-27)

Features

  • Make useAnimationFrame and useAnimationFrame loop generic and improve overall typing (7d69dd8)
  • Make useIdleCallback generic and improve overall typing (c5282d5)
  • Make useInterval generic and improve overall typing (3cc08aa)
  • Make useTimeout generic and improve overall typing (a65921a)

1.1.1 (2020-03-21)

Bug Fixes

  • Mark this package as side-effect-free to allow proper tree shaking (5cc805a)

1.1.0 (2020-03-21)

Features

  • Allow tree shaking by adding a es module export. (bee51c6)

Bug Fixes

  • Fix effect cleanups not being executed (useTimeoutEffect & useIdleCallbackEffect) (f62e393)

1.0.1 (2020-03-20)

Updated npm keywords.

🎉🎉🎉 1.0.0 (2020-03-20) 🎉🎉🎉

This package has now reached a state that justifies a version 1.0.0. Technically this is version 0.2.1 with a new README and a new dedicated API documentation (which you can view here). However, I want the public API to be considered stable at this point — which 0.X.X is not — hence the bump to 1.0.0.

Fell free to try it out and leave feedback on Github! :)

0.2.1 (2020-03-18)

Bug Fixes

0.2.0 (2020-03-18)

Features

  • useAnimationFrameLoop can now be stopped (854c9fb), closes #1

0.1.4 (2020-03-17)

Bug Fixes

  • Fix acorn security vulnerability (866e838)
  • Fix all security vulnarabilities except for minimist (eea30ea), closes #2

0.1.3 (2020-03-17)

Bug Fixes

  • Fix all security vulnarabilities except for minimist (9149df1)

0.1.2 (2019-11-08)

Bug Fixes

  • Fix example in documentation (44b0713)

0.1.1 (2019-11-08)

This release contains only documentation updates.

0.1.0 (2019-11-08)

Features

  • Added new hook "useAnimationFrame" (6808e6a)
  • Added new hook "useAnimationFrameLoop" (147067c)

Bug Fixes

  • Add callback type to index.js (38d7c6f)

0.1.0-alpha.6 (2019-11-08)

Features

  • Added new hook "useIdleCallback" (20cdc46)
  • Added new hook "useTimeout" (5ca6de6)

0.1.0-alpha.5 (2019-11-07)

Bug Fixes

0.1.0-alpha.4 (2019-11-07)

Bug Fixes

  • Added return types to index export (3ddb7ef)

0.1.0-alpha.3 (2019-11-07)

Features

  • Added hook "useIdleCallbackEffect" (b166e8f)

0.1.0-alpha.2 (2019-11-07)

Documentation

0.1.0-alpha.1 (2019-11-07)

Features

  • Added useInterval hook (799ac50)
  • First draft of useTimeoutEffect (b62a961)

0.1.0-alpha.0 (2019-10-25)

Features

  • First draft of useTimeoutEffect (59bffe3)