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
Name
Type
Description
callback
() => void
The function to be executed at each interval tick.
options.delay
number | null
Delay in milliseconds. If null, the interval will not start.
options.maxExecutions
number
The maximum number of times the interval should run before self-cancelling.
options.startOnMount
boolean
Whether the interval should begin automatically when the component mounts. Default: true.
Return values
Name
Type
Description
cancel
() => void
Stops the current interval and sets isActive to false.
executionCount
number
The total number of times the callback has been successfully executed.
isActive
boolean
Reactive state indicating if the interval is currently running.
reset
() => void
Clears the current interval, resets the executionCount to zero, and restarts.
start
() => void
Starts 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.