elements
lifecycle
browser
- useAudio
- useBattery
- useBluetooth
- useBreakpoints
- useBroadcastChannel
- useBrowserLocation
- useClipboard
- useCopy
- useCssVar
- useDisplayMedia
- useDocumentEvent
- useDocumentTitle
- useDocumentVisibility
- useEventListener
- useEventSource
- useEyeDropper
- useFavicon
- useFileSystemAccess
- useFps
- useFullscreen
- useGamepad
- useGeolocation
- useMeasure
- useMediaControls
- useMediaQuery
- useMemory
- useNetwork
- useObjectUrl
- useOnline
- useOtpCredential
- usePermission
- usePictureInPicture
- usePointerLock
- usePostMessage
- useRaf
- useShare
- useSpeechRecognition
- useSpeechSynthesis
- useSticky
utilities
state
user
sensors
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/reactuseUsage
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
| Name | Type | Default | Note |
|---|---|---|---|
| callback | UseRafCallback | - | The callback to execute |
| options.delay | number | - | The delay between each frame in milliseconds |
| options.enabled | boolean | true | Whether the callback should be enabled |
Returns
UseRafCallbackReturnContributors
ddebabin
Last updated on