TimerBeginnerSSR-safehooks/timer/useTimeout.ts

useTimeout

Run once after delay on mount/deps.

Import

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

API

Signature

useTimeout(fn, delay | null)

When to use

Use useTimeout 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 · useTimeout
Editor
function Toast() {
  const [show, setShow] = useState(true);
  useTimeout(() => setShow(false), show ? 3000 : null);
  return show ? <div>Saved</div> : null;
}
Preview

Implementation source

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

hooks/timer/useTimeout.ts
import { useEffect } from 'react';
import { useTimeoutFn } from './useTimeoutFn';

/**
 * Runs `fn` once after `delay` ms when mounted or when deps change.
 * Pass `null` delay to disable.
 */
export function useTimeout(
  fn: () => void,
  delay: number | null | undefined,
): ReturnType<typeof useTimeoutFn> {
  const controls = useTimeoutFn(fn, delay);

  useEffect(() => {
    controls.start();
    return controls.clear;
  }, [delay]);

  return controls;
}

Copy-paste example

useTimeout.example.tsx
'use client';

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

export function Toast() {
  const [show, setShow] = useState(true);
  useTimeout(() => setShow(false), show ? 3000 : null);
  return show ? <div>Saved</div> : null;
}

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/useTimeout.ts for implementation details