Created
July 20, 2019 14:30
-
-
Save alexanderson1993/72e2f2ecbc677fbea1aa75683ca01eda to your computer and use it in GitHub Desktop.
A hook that increments a value every 1 second.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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