hooks
useInterval

useInterval

A custom hook that provides functionalities for managing and controlling interval-based operations.

Add hook

Create a file use-interval.ts and copy & paste from useInterval.

import { useEffect, useRef, useState, useCallback } from 'react';
 
type IntervalFunction = () => void;
 
interface IntervalHookResult {
  isRunning: boolean;
  delay: number;
  startInterval: () => void;
  stopInterval: () => void;
  updateDelay: (newDelay: number) => void;
}
 
export const useInterval = (initialCallback: IntervalFunction, initialDelay: number): IntervalHookResult => {
  const [isRunning, setIsRunning] = useState<boolean>(true);
  const [delay, setDelay] = useState<number>(initialDelay);
  const savedCallback = useRef<IntervalFunction>(initialCallback);
 
  useEffect(() => {
    savedCallback.current = initialCallback;
  }, [initialCallback]);
 
  useEffect(() => {
    if (!isRunning) return undefined;
 
    const id = setInterval(() => savedCallback.current(), delay);
 
    return () => clearInterval(id);
  }, [delay, isRunning]);
 
  const startInterval = useCallback((): void => {
    setIsRunning(true);
  }, []);
 
  const stopInterval = useCallback((): void => {
    setIsRunning(false);
  }, []);
 
  const updateDelay = useCallback((newDelay: number): void => {
    setDelay(newDelay);
  }, []);
 
  return {
    isRunning,
    delay,
    startInterval,
    stopInterval,
    updateDelay,
  };
};

Usage

import React from 'react';
import { useInterval } from './hooks/use-interval';
 
function IntervalComponent() {
  const [count, setCount] = React.useState(0);
  const { isRunning, delay, startInterval, stopInterval, updateDelay } = useInterval(() => {
    setCount((prevCount) => prevCount + 1);
  }, 1000);
 
  return (
    <div>
      <h1>Interval Counter: {count}</h1>
      <p>Interval status: {isRunning ? 'Running' : 'Stopped'}</p>
      <p>Current delay: {delay}ms</p>
      <button onClick={startInterval}>Start Interval</button>
      <button onClick={stopInterval}>Stop Interval</button>
      <button onClick={() => updateDelay(2000)}>Update Delay to 2s</button>
    </div>
  );
}
 
export default IntervalComponent;

API

Parameters

NameTypeDescription
initialCallback() => voidThe function to be called at each interval.
initialDelaynumberThe initial delay in milliseconds between each interval call.

Returns

NameTypeDescription
isRunningbooleanIndicates whether the interval is currently running.
delaynumberThe current delay between interval calls in milliseconds.
startInterval() => voidFunction to start the interval.
stopInterval() => voidFunction to stop the interval.
updateDelay(newDelay: number) => voidFunction to update the interval delay.

Contributors

Avatar 1