React hooks for setTimeout, setInterval, requestAnimationFrame, requestIdleCallback
npm install react-timing-hooks


!types


useThrottledState(), useThrottle(), useDebounce()
useAnimationFrameLoop()
useCounter(), useCountdown(), useTimer()
useClock()
useTimeoutEffect(), useIdleCallbackEffect()
useOscillator()
bash
via npm
npm i react-timing-hooks
via yarn
yarn add react-timing-hooks
`
$3
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
}
`
----
#### 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
Result: {result}
}
`
----
#### 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 {currentTime}
}
`
----
#### 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 <>
>
}
`
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 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).
$3
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 <>
{counter}
>
}
`
#### 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 <>
{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 <>
{counter}
>
}
`
----
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 ? (
{output}
) : 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).
$3
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:
`javascript
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])
``