483

useRaf

Hook that defines the logic for raf callback

browserlowtest coverage
0frames per second
import { useRaf } from '@siberiacancode/reactuse';
import { useRef, useState } from 'react';

const Demo = () => {
  const [fps, setFps] = useState(0);
  const framesRef = useRef(0);
  const elapsedRef = useRef(0);

  useRaf(({ delta }) => {
    framesRef.current += 1;
    elapsedRef.current += delta;

    if (elapsedRef.current >= 1000) {
      setFps(Math.round((framesRef.current * 1000) / elapsedRef.current));
      framesRef.current = 0;
      elapsedRef.current = 0;
    }
  });

  return (
    <section className='flex flex-col items-center gap-2 p-8'>
      <span className='text-foreground font-mono text-6xl font-bold tabular-nums'>{fps}</span>
      <span className='text-muted-foreground text-sm'>frames per second</span>
    </section>
  );
};

export default Demo;
This hook uses requestAnimationFrame browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api

Installation

pnpm add @siberiacancode/reactuse

Usage

useRaf(() => console.log('callback'));

Type Declarations

export interface UseRafParams {
  /** The delta between each frame in milliseconds */
  delta: number;
  /** The timestamp of the current frame in milliseconds */
  timestamp: DOMHighResTimeStamp;
}

export type UseRafCallback = (params: UseRafParams) => void;

export interface UseRafOptions {
  /** The delay between each frame in milliseconds */
  delay?: number;
  /** Whether the callback should be enabled */
  enabled?: boolean;
}

export interface UseRafReturn {
  /** Whether the callback is active */
  active: boolean;
  /** Function to pause the callback */
  pause: () => void;
  /** Function to resume the callback */
  resume: () => void;
}

API

Parameters

NameTypeDefaultNote
callbackUseRafCallback-The callback to execute
options.delaynumber-The delay between each frame in milliseconds
options.enabledbooleantrueWhether the callback should be enabled

Returns

UseRafCallbackReturn

Contributors

ddebabin

Last updated on