UNPKG

1.88 kBPlain TextView Raw
1'use strict';
2import { useEffect, useRef } from 'react';
3import FrameCallbackRegistryJS from '../frameCallback/FrameCallbackRegistryJS';
4import type { FrameInfo } from '../frameCallback/FrameCallbackRegistryUI';
5
6/**
7 * @param setActive - A function that lets you start the frame callback or stop it from running.
8 * @param isActive - A boolean indicating whether a callback is running.
9 * @param callbackId - A number indicating a unique identifier of the frame callback.
10 * @see https://docs.swmansion.com/react-native-reanimated/docs/advanced/useFrameCallback#returns
11 */
12export type FrameCallback = {
13 setActive: (isActive: boolean) => void;
14 isActive: boolean;
15 callbackId: number;
16};
17const frameCallbackRegistry = new FrameCallbackRegistryJS();
18
19/**
20 * Lets you run a function on every frame update.
21 *
22 * @param callback - A function executed on every frame update.
23 * @param autostart - Whether the callback should start automatically. Defaults to `true`.
24 * @returns A frame callback object - {@link FrameCallback}.
25 * @see https://docs.swmansion.com/react-native-reanimated/docs/advanced/useFrameCallback
26 */
27export function useFrameCallback(
28 callback: (frameInfo: FrameInfo) => void,
29 autostart = true
30): FrameCallback {
31 const ref = useRef<FrameCallback>({
32 setActive: (isActive: boolean) => {
33 frameCallbackRegistry.manageStateFrameCallback(
34 ref.current.callbackId,
35 isActive
36 );
37 ref.current.isActive = isActive;
38 },
39 isActive: autostart,
40 callbackId: -1,
41 });
42
43 useEffect(() => {
44 ref.current.callbackId =
45 frameCallbackRegistry.registerFrameCallback(callback);
46 ref.current.setActive(ref.current.isActive);
47
48 return () => {
49 frameCallbackRegistry.unregisterFrameCallback(ref.current.callbackId);
50 ref.current.callbackId = -1;
51 };
52 }, [callback, autostart]);
53
54 return ref.current;
55}