Skip to content

Instantly share code, notes, and snippets.

@simsketch
Created September 2, 2020 15:38
Show Gist options
  • Save simsketch/f3e3c268fb5f7577e78e62b762df428d to your computer and use it in GitHub Desktop.
Save simsketch/f3e3c268fb5f7577e78e62b762df428d to your computer and use it in GitHub Desktop.
React useInterval in TypeScript
import React, { useState, useEffect, useRef } from 'react';
export function useInterval(callback: () => void, delay: number | null) {
const savedCallback = useRef<any>();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment