PerformanceIntermediateSSR-safehooks/performance/useRaf.ts

useRaf

requestAnimationFrame loop with start/stop.

Import

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

API

Signature

useRaf(callback, { enabled? }) → { isActive, start, stop }

When to use

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

SSR / Next.js

SSR-safe. Timers and rAF only run after mount / interactions.

Live playground

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

Live playgroundEdit · run with real @/hooks · useRaf
Editor
function Loop() {
  const { isActive, start, stop } = useRaf((time, delta) => {
    // animate with time / delta
  });
  return (
    <button onClick={isActive ? stop : start}>
      {isActive ? 'Stop' : 'Start'}
    </button>
  );
}
Preview

Implementation source

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

hooks/performance/useRaf.ts
import { useCallback, useEffect, useRef, useState } from 'react';
import { isBrowser } from '../utility/isBrowser';
import { useLatest } from '../utility/useLatest';

export interface UseRafOptions {
  /** Start the loop immediately. @default true */
  enabled?: boolean;
}

/**
 * requestAnimationFrame loop. Pass a callback invoked each frame.
 * Returns pause/resume controls and a running flag.
 */
export function useRaf(
  callback: (time: number, delta: number) => void,
  options: UseRafOptions = {},
): { isActive: boolean; start: () => void; stop: () => void } {
  const { enabled = true } = options;
  const [isActive, setIsActive] = useState(enabled);
  const cbRef = useLatest(callback);
  const rafRef = useRef<number | null>(null);
  const lastTimeRef = useRef<number | null>(null);

  const stop = useCallback(() => {
    if (rafRef.current !== null && isBrowser()) {
      cancelAnimationFrame(rafRef.current);
      rafRef.current = null;
    }
    lastTimeRef.current = null;
    setIsActive(false);
  }, []);

  const loop = useCallback(
    (time: number) => {
      const last = lastTimeRef.current ?? time;
      const delta = time - last;
      lastTimeRef.current = time;
      cbRef.current(time, delta);
      rafRef.current = requestAnimationFrame(loop);
    },
    [cbRef],
  );

  const start = useCallback(() => {
    if (!isBrowser()) return;
    if (rafRef.current !== null) return;
    setIsActive(true);
    rafRef.current = requestAnimationFrame(loop);
  }, [loop]);

  useEffect(() => {
    if (enabled) start();
    else stop();
    return stop;
  }, [enabled, start, stop]);

  return { isActive, start, stop };
}

Copy-paste example

useRaf.example.tsx
'use client';

import { useRaf } from '@/hooks';

export function Loop() {
  const { isActive, start, stop } = useRaf((time, delta) => {
    // animate with time / delta
  });
  return (
    <button onClick={isActive ? stop : start}>
      {isActive ? 'Stop' : 'Start'}
    </button>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Stable callbacks prevent child re-renders. Always cancel debounce on unmount (handled for you).
  • Source of truth: open hooks/performance/useRaf.ts for implementation details