Skip to content

Instantly share code, notes, and snippets.

@babakness
Created February 4, 2019 18:54
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save babakness/faca3b633bc23d9a0924efb069c9f1f5 to your computer and use it in GitHub Desktop.
Save babakness/faca3b633bc23d9a0924efb069c9f1f5 to your computer and use it in GitHub Desktop.
Typescript version of Dan Abramov's useInterval requiring non-null value for delay
import * as React from 'react'
const { useState, useEffect, useRef } = React
type IntervalFunction = () => ( unknown | void )
function useInterval( callback: IntervalFunction, delay: number ) {
const savedCallback = useRef<IntervalFunction| null>( null )
// Remember the latest callback.
useEffect( () => {
savedCallback.current = callback
} )
// Set up the interval.
useEffect( () => {
function tick() {
if ( savedCallback.current !== null ) {
savedCallback.current()
}
}
const id = setInterval( tick, delay )
return () => clearInterval( id )
}, [ delay ] )
}
@princefishthrower
Copy link

In both, 'useState' is declared but its value is never read. 😄 . (Also the case in Dan's original post)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment