• Custom React hook that provides an interval timer.

    It allows to execute a callback function repeatedly at a specified interval defined by the delay.

    Parameters

    • callback: (() => void)

      The function to be executed at each interval. The latest version of this callback is always invoked.

        • (): void
        • Returns void

    • delay: null | number

      The interval delay in milliseconds. If null, the interval will be paused

    Returns void

    Implementation Details

    • Callback Storage: The useRef hook is used to store the latest callback function. This ensures that the interval always invokes the most up-to-date version of the callback, without resetting the interval.
    • Interval Management: The setInterval function is used to execute the tick function at the specified delay. The interval is cleared using clearInterval when the component unmounts or the delay value changes.
    • Effect Trigger: A useEffect hook is employed twice: to update the savedCallback; to set up or clear the interval whenever the delay changes.
    • Error Prevention: If delay is null, the interval is not created, effectively pausing execution.

    Example

    import { useInterval } from 'react-playmakers';

    const Counter = () => {
    const [count, setCount] = useState(0);

    useInterval(() => {
    setCount(count + 1);
    }, 1000); // Increment count every 1 second.

    return <div>{count}</div>;
    };

Generated using TypeDoc