Skip to content

Instantly share code, notes, and snippets.

@gisderdube
Created February 6, 2019 13:13
Show Gist options
  • Save gisderdube/a1b16371a9da9b56a6f9285ab80469bc to your computer and use it in GitHub Desktop.
Save gisderdube/a1b16371a9da9b56a6f9285ab80469bc to your computer and use it in GitHub Desktop.
import React, { useEffect, useState, useRef } from 'react'
function useInterval(callback, delay) {
const savedCallback = useRef()
useEffect(() => {
savedCallback.current = callback
})
useEffect(() => {
function tick() {
savedCallback.current()
}
if (delay !== null) {
let id = setInterval(tick, delay)
return () => clearInterval(id)
}
}, [delay])
}
function Counter() {
const [count, setCount] = useState(0)
useInterval(() => {
setCount(count + 1)
}, 1000)
return (
<div>
Current count is: {count}
<br />
<button onClick={() => setCount(count + 1)}>Increase count</button>
</div>
)
}
export default Counter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment