Skip to content

Instantly share code, notes, and snippets.

@alexanderson1993
Created July 20, 2019 14:30
Show Gist options
  • Save alexanderson1993/72e2f2ecbc677fbea1aa75683ca01eda to your computer and use it in GitHub Desktop.
Save alexanderson1993/72e2f2ecbc677fbea1aa75683ca01eda to your computer and use it in GitHub Desktop.
A hook that increments a value every 1 second.
import React from 'react'
export default function useCounter(initialCount) {
const [time, setTime] = React.useState(initialCount);
// The timer might not be exactly 1000 ms, so track the time
// between intervals manually
const lastTimeRef = React.useRef(Date.now())
// This effect resets the timer to the initial count when it changes.
React.useEffect(() => {
setTime(initialCount)
},[initialCount])
// See https://overreacted.io/making-setinterval-declarative-with-react-hooks/
// for an implementation of this hook
useInterval(() => {
setTime(time => time + Date.now() - lastTimeRef.current)
lastTimeRef.current = Date.now()
},1000)
return time;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment