Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@MOTORIST MOTORIST commented Jan 23, 2020

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

This comment has been minimized.

Copy link

@princefishthrower princefishthrower commented Sep 2, 2020

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