npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

use-interval-react-lite

v1.0.0

Published

Declarative React 18 & 19 interval and timeout hooks with dynamic delay, pause, resume, and immediate execution.

Readme

use-interval-react-lite

Declarative React 18 & 19 interval and timeout hooks with dynamic delay, pause, resume, and immediate execution support.

npm version npm downloads license bundle size sponsor


Why use-interval-react-lite?

Using setInterval natively inside React's useEffect is infamous for causing bugs:

  1. Stale Closures: If your callback captures state or props, it gets frozen at the moment the interval was created unless listed in dependencies. Adding dependencies frequently clears and restarts the interval, resetting your timer cycle.
  2. Missing Controls: Pausing, resuming, or resetting a standard interval requires cumbersome boolean state flags and manual ref tracking.
  3. Delayed First Execution: Standard intervals wait until the first full duration completes before running for the first time.
  4. React 18 & 19 Strict Mode Double Mounts: Can easily spawn zombie intervals if cleanup handlers aren't meticulously crafted.

use-interval-react-lite solves this declaratively:

  • No Stale Closures: Internally saves your callback in a ref, allowing your function to always access the freshest state without restarting the timer.
  • Dynamic Controls: Out of the box pause(), resume(), reset(), and isActive boolean.
  • Dynamic Delay & Pausing: Set delayMs to null or call pause() to effortlessly suspend ticking.
  • Immediate Execution: Support for { immediate: true } to invoke the callback right away on mount or resume.
  • Bonus useTimeout: Declarative timeout hook with clear() and reset() helpers.
  • Zero Runtime Dependencies: Ultra-lightweight (<600 bytes minified & gzipped).

Installation

Install using your preferred package manager:

# npm
npm install use-interval-react-lite

# pnpm
pnpm add use-interval-react-lite

# yarn
yarn add use-interval-react-lite

# bun
bun add use-interval-react-lite

Quick Start

import React, { useState } from 'react';
import { useInterval } from 'use-interval-react-lite';

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

  // Increments every 1000ms. Always has access to latest state!
  const { pause, resume, reset, isActive } = useInterval(() => {
    setCount((prev) => prev + 1);
  }, 1000);

  return (
    <div>
      <h2>Count: {count}</h2>
      <p>Status: {isActive ? 'Running' : 'Paused'}</p>
      <button onClick={pause}>Pause</button>
      <button onClick={resume}>Resume</button>
      <button onClick={reset}>Reset Timer Cycle</button>
    </div>
  );
}

Real-World Examples

Example 1: Polling an API with Dynamic Frequency

Easily switch between fast polling when active and slow polling when idle, or pause entirely:

import React, { useState } from 'react';
import { useInterval } from 'use-interval-react-lite';

export function LiveStockTicker({ symbol }: { symbol: string }) {
  const [price, setPrice] = useState<number | null>(null);
  const [pollingRate, setPollingRate] = useState<number | null>(3000); // 3 seconds

  const fetchPrice = async () => {
    const res = await fetch(`/api/stocks/${symbol}`);
    const data = await res.json();
    setPrice(data.price);
  };

  // Run fetchPrice immediately on start, then every pollingRate ms
  useInterval(fetchPrice, pollingRate, { immediate: true });

  return (
    <div>
      <h3>{symbol}: {price ? `$${price.toFixed(2)}` : 'Loading...'}</h3>
      <div>
        <button onClick={() => setPollingRate(1000)}>High Speed (1s)</button>
        <button onClick={() => setPollingRate(5000)}>Normal (5s)</button>
        <button onClick={() => setPollingRate(null)}>Stop Polling</button>
      </div>
    </div>
  );
}

Example 2: Interactive Stopwatch with Pause & Resume

Build complete stopwatch or countdown components with declarative controls:

import React, { useState } from 'react';
import { useInterval } from 'use-interval-react-lite';

export function Stopwatch() {
  const [seconds, setSeconds] = useState(0);

  const { pause, resume, reset, isActive } = useInterval(
    () => setSeconds((s) => s + 1),
    1000
  );

  const handleFullReset = () => {
    reset();
    setSeconds(0);
  };

  return (
    <div className="stopwatch">
      <h1>{seconds}s</h1>
      <button onClick={isActive ? pause : resume}>
        {isActive ? 'Pause' : 'Resume'}
      </button>
      <button onClick={handleFullReset}>Reset</button>
    </div>
  );
}

Example 3: Auto-Dismiss Toast Alert with useTimeout

Dismiss flash banners automatically after a preset duration, with ability to hover and cancel:

import React, { useState } from 'react';
import { useTimeout } from 'use-interval-react-lite';

export function ToastMessage({ message, onDismiss }: { message: string; onDismiss: () => void }) {
  const [delay, setDelay] = useState<number | null>(4000); // 4 seconds

  const { clear, reset } = useTimeout(() => {
    onDismiss();
  }, delay);

  return (
    <div
      className="toast-alert"
      onMouseEnter={clear} // pause timeout when user hovers
      onMouseLeave={reset} // restart countdown when user leaves
    >
      <span>{message}</span>
      <button onClick={onDismiss}>&times;</button>
    </div>
  );
}

API Reference

useInterval(callback, delayMs, options?)

| Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | callback | () => void | required | Function called on each interval tick | | delayMs | number \| null | required | Interval duration in milliseconds. Pass null to suspend. | | options.immediate| boolean | false | When true, fires callback immediately on mount / resume |

Returns IntervalControls:

  • pause: () => void - Suspends the running interval without clearing state.
  • resume: () => void - Resumes the interval if paused.
  • reset: () => void - Resets and restarts the interval clock cycle.
  • isActive: boolean - True if currently running and ticking.

useTimeout(callback, delayMs)

| Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | callback | () => void | required | Function executed after timeout completes | | delayMs | number \| null | required | Delay in milliseconds, or null to disable |

Returns TimeoutControls:

  • reset: () => void - Restarts the timeout timer.
  • clear: () => void - Cancels the pending timeout.
  • isPending: boolean - True if the timer is currently waiting to fire.

TypeScript Types

export interface UseIntervalOptions {
  immediate?: boolean;
}

export interface IntervalControls {
  pause: () => void;
  resume: () => void;
  reset: () => void;
  isActive: boolean;
}

export interface TimeoutControls {
  reset: () => void;
  clear: () => void;
  isPending: boolean;
}

Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.


License

MIT © Pirapaakaran Pirathapan

Support & Sponsor

If you find this hook useful in your React projects, please consider supporting my open-source work:

💖 Sponsor Piratha97 on GitHub