Skip to main content Link Search Menu Expand Document (external link)

useInterval

A react wrapper for setInterval – no leaks on unmount!

This hook allows you to do certain actions at a regular interval, i.e. loops. It is a react-wrapper for the native javascript function setInterval.

In addition to the standard Javascript API, the returned callbacks allow you to pause, resume, stop and start the interval, too.

Note: By default, the interval is stopped on mount and has to be started manually. If you want the interval to start immediately on mount, use options.startOnMount.

You can also stop the interval or start the interval in a stopped state by setting a delay value of null.

If you want to loop very fast – maybe because you want to animate something – you might want to use useAnimationFrameLoop() instead which yields better performance in these cases.

If you only want to increase or decrease a numeric value in a regular interval, take a look at useCounter().

Example

Simple interval that starts immediately on mount

import { useInterval } from 'react-timing-hooks'

// Increase count every 200 milliseconds
const [count, setCount] = useState(0)
const increaseCount = () => setCount(count + 1)
useInterval(increaseCount, 200, { startOnMount: true })

Pausing and resuming an interval

import { useInterval } from 'react-timing-hooks'

const [count, setCount] = useState(0)
const increaseCount = () => setCount(count + 1)
const {
  start,
  pause,
  resume,
  isPaused
} = useInterval(increaseCount, 200)

return <div>
  <button onClick={start}>Start!</button>
  <button onClick={isPaused ? resume : pause}>
    {isPaused ? "Resume" : "Pause"}
  </button>
</div>

API

Params

useInterval(callback, delay, options = {})

Name Default Description
callback is required A function that will be invoked as soon as the timeout expires
delay is required A number or null. If numeric, it is the delay between each execution of callback. See setInterval(). If set to null, the interval will stop.
options.startOnMount false If true, the counter will immediately start on mount. If false, it has to be started manually via start().

Return value

An object of interval controls:

Name Description
isPaused A boolean that indicates whether the interval is currently paused
isStopped A boolean that indicates whether the interval is currently stopped. Meaning it cannot be resumed, but only restarted via start().
pause A function that will temporarily pause the interval without destroying it
resume A function that resumes a paused interval
stop A function that stops and destroys(!) the interval.
start A function that restarts a stopped interval

Notes

Pending intervals will be cleared upon unmount.