Skip to content

Instantly share code, notes, and snippets.

@babakness
Created February 4, 2019 18:54
Show Gist options
  • 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 ] )
}
@MOTORIST
Copy link

delay: number | null

import * as React from 'react'

const { useState, useEffect, useRef } = React

type IntervalFunction = () => ( unknown | void )

function useInterval( callback: IntervalFunction, delay: number | null ) {

  const savedCallback = useRef<IntervalFunction| null>( null )

  useEffect( () => {
    if (delay === null) return;
    savedCallback.current = callback
  } )

  useEffect( () => {
     if (delay === null) return;
    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