useIntervalSafe

A declarative and robust React hook for managing setInterval lifecycles with execution limits and manual controls.

Note

Setting the delay to null or undefined will prevent the interval from starting or will pause it if it is already running.

Installation

bash

Description

The useIntervalSafe hook provides a safe way to handle intervals in React by using a ref for the callback to prevent stale closures. It extends the native setInterval functionality by adding features such as execution capping (maxExecutions), start on mount, and a managed isActive state. It is designed to be SSR-safe and automatically cleans up the interval when the component unmounts to prevent memory leaks.

Parameters

NameTypeDescription
callback() => voidThe function to be executed at each interval tick.
options.delaynumber | nullDelay in milliseconds. If null, the interval will not start.
options.maxExecutionsnumberThe maximum number of times the interval should run before self-cancelling.
options.startOnMountbooleanWhether the interval should begin automatically when the component mounts. Default: true.

Return values

NameTypeDescription
cancel() => voidStops the current interval and sets isActive to false.
executionCountnumberThe total number of times the callback has been successfully executed.
isActivebooleanReactive state indicating if the interval is currently running.
reset() => voidClears the current interval, resets the executionCount to zero, and restarts.
start() => voidStarts or restarts the interval based on the current configuration.

Demo

Interval Safe

Status: Idle
Execution:0/6
This interval is configured to stop automatically after 6 ticks.

Source code

tsx