Created
February 4, 2019 18:54
-
-
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
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 * 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 ] ) | |
} |
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
delay: number | null