TimerBeginnerSSR-safehooks/timer/useIntervalWhen.ts

useIntervalWhen

Interval only while condition is true.

Import

TypeScript
import { useIntervalWhen } from '@/hooks';

API

Signature

useIntervalWhen(fn, delay, when, options?)

When to use

Use useIntervalWhen instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Timers start in effects — no server timers.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useIntervalWhen
Editor
function Live({ live }: { live: boolean }) {
  const [t, setT] = useState(0);
  useIntervalWhen(() => setT(Date.now()), 1000, live);
  return <p>{t}</p>;
}
Preview

Implementation source

Full library source for useIntervalWhen — copy into your project when you are not installing a package yet.

hooks/timer/useIntervalWhen.ts
import { useInterval } from './useInterval';

/**
 * Interval that only runs while `when` is true.
 */
export function useIntervalWhen(
  fn: () => void,
  delay: number | null | undefined,
  when: boolean,
  options?: { immediate?: boolean },
): ReturnType<typeof useInterval> {
  return useInterval(fn, when ? delay : null, {
    immediate: options?.immediate,
    autoStart: when,
  });
}

Copy-paste example

useIntervalWhen.example.tsx
'use client';

import { useState } from 'react';
import { useIntervalWhen } from '@/hooks';

export function Live({ live }: { live: boolean }) {
  const [t, setT] = useState(0);
  useIntervalWhen(() => setT(Date.now()), 1000, live);
  return <p>{t}</p>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Pass null delay to pause/disable intervals and timeouts without unmounting.
  • Source of truth: open hooks/timer/useIntervalWhen.ts for implementation details