### Run development commands for pretty-react-hooks Source: https://github.com/littensy/pretty-react-hooks/blob/master/README.md Commands to get started with development on the `pretty-react-hooks` project, including enabling watch mode with TestEZ Companion support and compiling the package's output directory. ```Shell pnpm dev pnpm build ``` -------------------------------- ### Install pretty-react-hooks package Source: https://github.com/littensy/pretty-react-hooks/blob/master/README.md Instructions for installing the `pretty-react-hooks` package, which provides useful React hooks and utilities for Roblox TypeScript projects, using npm, yarn, or pnpm. ```Shell npm install @rbxts/pretty-react-hooks yarn add @rbxts/pretty-react-hooks pnpm add @rbxts/pretty-react-hooks ``` -------------------------------- ### React Component Example Using useKeyPress Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-key-press/README.md Example React component demonstrating the usage of `useKeyPress` to detect single key presses (Space) and key combinations (Ctrl+A), logging their states to the console using `useEffect`. ```tsx function Keyboard() { const spacePressed = useKeyPress(["Space"]); const ctrlAPressed = useKeyPress(["LeftControl+A", "RightControl+A"]); useEffect(() => { print(`Space pressed: ${spacePressed}`); }, [spacePressed]); useEffect(() => { print(`Ctrl+A pressed: ${ctrlAPressed}`); }, [ctrlAPressed]); return undefined!; } ``` -------------------------------- ### useAsync Hook Usage Example (TSX) Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async/README.md Provides a practical example of how to integrate `useAsync` into a React functional component. This snippet demonstrates fetching an asynchronous resource (`Workspace.WaitForChild`) and conditionally rendering based on its availability, using `createPortal`. ```tsx function BaseplatePortal(props: React.PropsWithChildren) { const [baseplate] = useAsync(async () => { return Workspace.WaitForChild("Baseplate"); }); if (!baseplate) { return undefined!; } return createPortal(props.children, baseplate); } ``` -------------------------------- ### useCamera Hook Usage Example with createPortal Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-camera/README.md Demonstrates how to use the useCamera hook to obtain the current camera and then utilize it with createPortal to render UI elements relative to the camera's position. This example shows a simple 'Hello, World!' text label attached to the camera. ```tsx function CameraPortal() { const camera = useCamera(); return createPortal(, camera); } ``` -------------------------------- ### Example: Using useTagged to get instances by tag Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-tagged/README.md Demonstrates a basic usage of the `useTagged` hook to retrieve all instances with the tag 'Zombie' and render a `ZombieHealthbar` component for each. ```tsx function ZombieHealth() { const zombies = useTagged("Zombie"); return ( <> {zombies.map((zombie) => ( ))} ); } ``` -------------------------------- ### TSX Example: Using useAsyncCallback to Fetch Baseplate Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async-callback/README.md Illustrates a practical application of `useAsyncCallback` within a React component to asynchronously fetch a 'Baseplate' from `Workspace`. The example demonstrates how to manage and display the async operation's status, update the UI based on the state, and trigger the async call via a user interaction. ```tsx function GetBaseplate() { const [state, getBaseplate] = useAsyncCallback(async () => { return Workspace.WaitForChild("Baseplate"); }); useEffect(() => { print("Baseplate", state.status, state.value); }, [state]); return ( getBaseplate(), }} /> ); } ``` -------------------------------- ### Example: Tracking Key Presses with useDeferState Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-defer-state/README.md Illustrates a practical application of `useDeferState` in a React `Counter` component to efficiently track keys being pressed and released. It demonstrates how to integrate with `useEventListener` for input handling and `useEffect` for side effects, showcasing the performance benefits of deferred state updates. ```tsx function Counter() { const [keysDown, setKeysDown] = useDeferState([]); useEventListener(UserInputService.InputBegan, (input) => { setKeysDown((keysDown) => [...keysDown, input.KeyCode.Name]); }); useEventListener(UserInputService.InputEnded, (input) => { setKeysDown((keysDown) => keysDown.filter((key) => key !== input.KeyCode.Name)); }); useEffect(() => { print(keysDown); }, [keysDown]); return ; } ``` -------------------------------- ### React Component Example: Pulsating Transparency with useLifetime Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-lifetime/README.md Demonstrates how to use the `useLifetime` hook within a React component to create a dynamic visual effect. The `Blink` component uses the hook to get elapsed time, which is then mapped to a sine wave to control the `BackgroundTransparency` of a frame, resulting in a pulsating effect. ```tsx function Blink() { const lifetime = useLifetime(); const transparency = lifetime.map((t) => math.sin(t) * 0.5 + 0.5); return ; } ``` -------------------------------- ### React Component Example using useBindingState Hook Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-binding-state/README.md Illustrates the practical application of the 'useBindingState' hook within a React functional component. This example demonstrates how to subscribe to a 'visible' prop (which can be a boolean or a binding) and use 'useEffect' to react to changes in its resolved value, updating the component's UI accordingly. ```tsx interface Props { visible: boolean | Binding; } function ToggleFrame({ visible }: Props) { const isVisible = useBindingState(visible); useEffect(() => { print("Visible changed to", isVisible); }, [isVisible]); return ; } ``` -------------------------------- ### Example Usage of useThrottleState Hook in React Component Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-throttle-state/README.md Demonstrates how to use the `useThrottleState` hook within a React component to throttle updates to the viewport size. This example ensures that viewport updates are processed at most once per second, improving performance. ```TSX function ViewportProvider() { const camera = useCamera(); const [viewport, setViewport] = useThrottleState(camera.ViewportSize, { time: 1 }); useEventListener(camera.GetPropertyChangedSignal("ViewportSize"), () => { setViewport(camera.ViewportSize); }); return ; } ``` -------------------------------- ### Example Usage of useUnmountEffect Hook in React Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-unmount-effect/README.md Illustrates how to integrate and use the `useUnmountEffect` hook within a React functional component. This example demonstrates logging a message to the console when the `UnmountLogger` component is unmounted. ```tsx function UnmountLogger() { useUnmountEffect(() => { print("Unmounting..."); }); return ; } ``` -------------------------------- ### Example Usage of useAsyncEffect in React Component Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async-effect/README.md Demonstrates how to use `useAsyncEffect` within a React functional component to manage an asynchronous countdown. The example shows setting up a counter that updates over time, ensuring the effect is managed correctly. ```tsx function Countdown() { const [counter, setCounter] = useState(0); useAsyncEffect(async () => { return setCountdown((countdown) => { setCounter(countdown); }, 10); }, []); return ; } ``` -------------------------------- ### React Component Example using useMotion for Hover Effect Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-motion/README.md Illustrates the practical application of the `useMotion` hook within a React component. It demonstrates how to animate a button's background transparency on `MouseEnter` and `MouseLeave` events using the returned `hoverMotor` and `hover` binding. ```tsx function Button() { const [hover, hoverMotor] = useMotion(0); return ( hoverMotor.spring(1, config.spring.stiff), MouseLeave: () => hoverMotor.spring(0, config.spring.stiff) }} Size={new UDim2(0, 100, 0, 100)} BackgroundTransparency={hover.map((t) => lerp(0.8, 0.5, t))} /> ); } ``` -------------------------------- ### Example: Animating Button Color with useSpring Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-spring/README.md Demonstrates how to use the `useSpring` hook within a React component to animate a button's background color based on its props, applying a stiff spring configuration for the animation. ```tsx function Button({ color }: Props) { const color = useSpring(color, config.spring.stiff); return ( ); } ``` -------------------------------- ### Example: React Component Using useMouse Hook Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-mouse/README.md Demonstrates how to integrate the `useMouse` hook into a React functional component. It tracks the mouse position and updates a UI element's position accordingly, showcasing real-time interaction. ```tsx function MouseTracker() { const mouse = useMouse(); return ( UDim2.fromOffset(p.X, p.Y))} /> ); } ``` -------------------------------- ### TSX: Example Usage of useTimer Hook Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-timer/README.md Illustrates how to use the `useTimer` hook within a React component to create a blinking effect. The example demonstrates accessing the timer's value and resetting it on a button click. ```tsx function Blink() { const timer = useTimer(); const transparency = timer.value.map((t) => math.sin(t) * 0.5 + 0.5); return ( timer.reset(), }} /> ); } ``` -------------------------------- ### TSX Example: Debouncing User Input for Search Query Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-debounce-callback/README.md An example demonstrating the practical application of `useDebounceCallback` in a React component. It shows how to debounce text input from a textbox to update a search query state only after the user has paused typing for 1 second, optimizing performance by reducing frequent state updates. ```tsx function SearchQuery() { const [query, setQuery] = useState(""); const debounced = useDebounceCallback((value: string) => { setQuery(value); }, 1); return ( debounced.run(rbx.Text), }} /> ); } ``` -------------------------------- ### TSX: Example of useDebounceEffect for Search Query Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-debounce-effect/README.md Illustrates the practical application of `useDebounceEffect` in a React component to debounce user input for a search query. The example demonstrates how to delay an action (printing the query) until the user has stopped typing for a specified duration, improving performance and user experience by preventing excessive re-renders or API calls. ```tsx function SearchQuery() { const [query, setQuery] = useState(""); useDebounceEffect( () => { print(query); }, [query], { wait: 1 }, ); return ( setQuery(rbx.Text), }} /> ); } ``` -------------------------------- ### TSX: Example Usage of useLatest in a Counter Component Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-latest/README.md An example demonstrating the `useLatest` hook in a React `Counter` component. It shows how `latestValue.current` always reflects the most recent state, even within a `useEventListener` callback, preventing stale closure issues. ```TSX function Counter() { const [value, setValue] = useState(0); const latestValue = useLatest(value); useEventListener(RunService.Heartbeat, () => { print(latestValue.current); }); return ( setValue(value + 1), }} /> ); } ``` -------------------------------- ### TSX Example: Throttling Viewport Size Updates Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-throttle-effect/README.md Illustrates how to use `useThrottleEffect` within a React component to throttle updates to state based on viewport size changes. This example demonstrates integrating the hook with `useEventListener` and `useState` to manage and display throttled updates efficiently. ```tsx function ResizeLogger() { const camera = useCamera(); const [viewport, setViewport] = useState(camera.ViewportSize); useEventListener(camera.GetPropertyChangedSignal("ViewportSize"), () => { setViewport(camera.ViewportSize); }); useThrottleEffect( () => { print("Viewport size updated:", viewport); }, [viewport], { time: 1 }, ); return ; } ``` -------------------------------- ### TypeScript JSX: Example Usage of useMountEffect Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-mount-effect/README.md Demonstrates how to integrate and use the `useMountEffect` hook within a React functional component, specifically for executing code upon component mounting. ```tsx function MountLogger() { useMountEffect(() => { print("Mounted"); }); return ; } ``` -------------------------------- ### Example Usage of useEventListener Hook Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-event-listener/README.md Illustrates how to use the `useEventListener` hook within a React component to listen for a 'PlayerAdded' event. ```tsx function PlayerJoined() { useEventListener(Players.PlayerAdded, (player) => { print(`${player.DisplayName} joined!`); }); return ; } ``` -------------------------------- ### Example: Using useTimeout to Increment Count Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-timeout/README.md Demonstrates how to use the `useTimeout` hook within a React functional component to increment a counter after a one-second delay. This example showcases the hook's ability to manage timed actions in a component. ```tsx function CountOne() { const [count, setCount] = useState(0); useTimeout(() => { setCount(count + 1); }, 1); return ; } ``` -------------------------------- ### Example Usage of useBindingListener Hook in React Component Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-binding-listener/README.md Illustrates how to use the `useBindingListener` hook within a React functional component. It demonstrates subscribing to a `transparency` binding and logging its updates, then applying the binding to a `textbutton`'s `BackgroundTransparency` property. ```tsx interface Props { transparency: number | Binding; } function TransparentFrame({ transparency }: Props) { useBindingListener(transparency, (value) => { print("Binding updated to", value); }); return ; } ``` -------------------------------- ### Example: Using useViewport to Adjust Text Size Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-viewport/README.md Demonstrates how to use the `useViewport` hook within a React component to dynamically adjust text size based on the current viewport dimensions. It calculates a scaled text size using `math.min`. ```tsx function TextSize() { const viewport = useViewport(); const textSize = viewport.map((size) => { return math.min(size.X / 1920, size.Y / 1080) * 14; }); return ; } ``` -------------------------------- ### Example Usage of useUpdateEffect in React Component Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-update-effect/README.md This example demonstrates how to integrate `useUpdateEffect` into a React functional component. The `RenderLogger` component uses the hook to print 'Updated' only when its state changes, effectively showing that the effect is skipped on the initial render and only triggers on subsequent updates. ```TSX function RenderLogger() { const [state, setState] = useState(0); useUpdateEffect(() => { print("Updated"); }); return ( setState(state + 1), }} /> ); } ``` -------------------------------- ### Implement React Component with useLatestCallback Hook (TSX) Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-latest-callback/README.md Illustrates the practical application of `useLatestCallback` within a React `Stepper` component. This example demonstrates how to ensure an `useEffect` hook consistently invokes the most current version of a prop function (`onStep`), effectively preventing common stale closure issues in React. ```tsx interface Props { onStep: () => void; } function Stepper({ onStep }: Props) { const onStepCallback = useLatestCallback(onStep); useEffect(() => { // Will always call the latest version of `onStep` const connection = RunService.RenderStepped.Connect(onStepCallback); return () => { connection.Disconnect(); }; }, []); return undefined!; } ``` -------------------------------- ### Example: Using useComposedRef in a DraggableFrame Component Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-composed-ref/README.md Demonstrates how to integrate the `useComposedRef` hook within a React component. This example shows combining an external ref prop with an internal state setter to manage a DOM element, enabling a draggable functionality via a `useEffect` hook. ```tsx interface Props { ref?: RefFunction; } function DraggableFrame({ ref }: Props) { const [frame, setFrame] = useState(); const composedRef = useComposedRef(ref, setFrame); useEffect(() => { const handle = makeDraggable(frame); return () => { handle.disconnect(); }; }, [frame]); return ; } ``` -------------------------------- ### Example Usage of useUpdate Hook in React Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-update/README.md This example demonstrates how to integrate the `useUpdate` hook into a React functional component named `RenderLogger`. It uses `setInterval` to periodically call the update function, forcing re-renders, and logs messages to track when the component renders due to the hook and other reasons. ```tsx function RenderLogger() { const update = useUpdate(); useEffect(() => { return setInterval(() => { update(); }, 1); }, []); useEffect(() => { print("Rendered because of useUpdate"); }, [update]); print("Rendered"); return ; } ``` -------------------------------- ### Example Usage of useDeferCallback in a React Component Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-defer-callback/README.md Demonstrates how to use the `useDeferCallback` hook within a React `Counter` component. It shows deferring `setCount` updates, integrating with an event listener for user input, and cleaning up the deferred call using `useUnmountEffect` to prevent memory leaks. ```tsx function Counter() { const [count, setCount] = useState(0); const [deferredSetCount, cancel] = useDeferCallback(setCount); useEventListener(UserInputService.InputBegan, (input) => { if (input.KeyCode === Enum.KeyCode.E) { deferredSetCount(count + 1); } }); useUnmountEffect(cancel); return ; } ``` -------------------------------- ### React Component Using useInterval Hook Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-interval/README.md An example React functional component demonstrating the practical application of the `useInterval` hook to create a simple counter that updates every second. ```tsx function Interval() { const [count, setCount] = useState(0); useInterval(() => { setCount(count + 1); }, 1); return ; } ``` -------------------------------- ### Example: Debouncing Search Query Input with useDebounceState Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-debounce-state/README.md Illustrates how to apply the `useDebounceState` hook to a text input field, updating a `query` state only after a 1-second delay from the last user input, optimizing performance for search functionalities. ```tsx function SearchQuery() { const [query, setQuery] = useDebounceState("", { wait: 1 }); useEffect(() => { print(query); }, [query]); return ( setQuery(rbx.Text), }} /> ); } ``` -------------------------------- ### Example: Throttling Viewport Size Updates with useThrottleCallback Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-throttle-callback/README.md Illustrates the practical application of `useThrottleCallback` within a React component to efficiently manage and throttle updates to the viewport size, preventing excessive re-renders on frequent `ViewportSize` changes. ```tsx function ViewportProvider() { const camera = useCamera(); const [viewport, setViewport] = useState(camera.ViewportSize); const throttled = useThrottleCallback((size: Vector2) => { setViewport(size); }, 1); useEventListener(camera.GetPropertyChangedSignal("ViewportSize"), () => { throttled.run(camera.ViewportSize); }); return ; } ``` -------------------------------- ### Example: Using useTagged with custom type casting Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-tagged/README.md Illustrates how to apply a custom TypeScript interface (`ZombieModel`) to the instances returned by `useTagged`, ensuring type safety and access to specific properties like `Health`. ```tsx interface ZombieModel extends Model { Health: NumberValue; } function ZombieHealth() { const zombies = useTagged("Zombie"); return ( <> {zombies.map((zombie) => ( ))} ); } ``` -------------------------------- ### useAsync Unsafe State Update Example (TypeScript) Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async/README.md Illustrates a critical warning regarding the use of `await` within `useAsync` callbacks when updating component state. It highlights the risk of state updates occurring after a component has unmounted, leading to potential memory leaks or errors. ```ts useAsync(async () => { await Promise.delay(5); setState("Hello World!"); // unsafe }); ``` -------------------------------- ### Implement Counter with useDeferEffect Hook (React TSX) Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-defer-effect/README.md This example demonstrates how to use the `useDeferEffect` hook in a React functional component. It creates a simple counter that updates and prints its value, ensuring the effect is deferred until the next Heartbeat frame. ```tsx function Counter() { const [count, setCount] = useState(0); useDeferEffect(() => { print(count); }, [count]); return ( setCount((count) => count + 1), }} /> ); } ``` -------------------------------- ### TypeScript Unsafe State Update with useAsyncCallback and Await Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async-callback/README.md This example highlights a critical warning: using `await` with state updates inside `useAsyncCallback` can be unsafe. If the promise is cancelled, the thread might still resume after component unmount, leading to potential memory leaks or errors when `setState` is called on an unmounted component. ```ts useAsyncCallback(async () => { await Promise.delay(5); setState("Hello World!"); // unsafe }); ``` -------------------------------- ### useKeyPress Hook Parameters Documentation Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-key-press/README.md Documents the parameters for the `useKeyPress` hook, including `keyCodes` and the optional `options` object with its nested properties and their default values. ```APIDOC keyCodes: KeyCodes[] - One or more key codes. options?: KeyPressOptions - Optional options object. bindAction: boolean = false - Whether to bind a ContextActionService action to the key press. actionName: string = "random string" - The name of the action to bind. actionPriority: Enum.ContextActionPriority.High.Value - The priority of the action to bind. actionInputTypes: Array = [Keyboard, Gamepad1] - The input types of the action to bind. ``` -------------------------------- ### useAsync Hook Parameters (APIDOC) Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async/README.md Documents the parameters accepted by the `useAsync` hook, detailing their purpose and default values. ```APIDOC - callback: The async function to run. - deps: The dependencies to watch for changes. Defaults to an empty array. ``` -------------------------------- ### useDeferCallback Hook API Reference Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-defer-callback/README.md Detailed API documentation for the `useDeferCallback` hook, outlining its input parameters and the structure of its returned values. This section clarifies the purpose and expected types for each part of the hook's interface. ```APIDOC useDeferCallback: Parameters: callback: The function to defer. Returns: execute: The deferred function. cleanup: A function that will cancel a scheduled update. ``` -------------------------------- ### APIDOC: useLatest Hook Parameters and Return Value Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-latest/README.md Detailed API documentation for the `useLatest` hook, outlining its input parameters (`value`, `isEqual`) and the structure of the returned ref object. ```APIDOC Parameters: - `value`: The value to wrap in a ref. - `isEqual?`: An optional equality function. Defaults to a strict equality check (`===`). Returns: - A ref object with a `current` property pointing to the latest value. ``` -------------------------------- ### APIDOC: useBindingState Hook Parameters and Returns Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-binding-state/README.md Provides detailed documentation for the 'useBindingState' hook, outlining its required 'binding' parameter and describing the type of value it returns. ```APIDOC Parameters: binding: The binding to subscribe to. Returns: The value of the binding. ``` -------------------------------- ### Document useLatestCallback Hook Parameters and Returns (APIDOC) Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-latest-callback/README.md Provides API documentation for the `useLatestCallback` hook. It details the `callback` parameter, which is the function to be memoized, and describes the return value as the stable, memoized version of that callback. ```APIDOC Parameters: - callback: The callback to memoize. Returns: - The memoized callback. ``` -------------------------------- ### useDebounceState Hook API Reference Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-debounce-state/README.md Detailed API documentation for the `useDebounceState` hook, including its signature, parameters, and return values, explaining how to configure its debouncing behavior. ```APIDOC useDebounceState(initialState: T, options?: UseDebounceOptions): LuaTuple<[T, Dispatch>]> Description: Delays updating state until after wait seconds have elapsed since the last time the debounced function was invoked. Set to the most recently passed state after the delay. Parameters: initialState: The initial state. options: The options object. wait: The number of seconds to delay. Defaults to 0. leading: Specify invoking on the leading edge of the timeout. Defaults to false. trailing: Specify invoking on the trailing edge of the timeout. Defaults to true. maxWait: The maximum time state is allowed to be delayed before invoking. Returns: The debounced state. A function to update the debounced state. ``` -------------------------------- ### APIDOC: useDebounceEffect Hook Parameters and Returns Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-debounce-effect/README.md Detailed API documentation for the `useDebounceEffect` hook, specifying its input parameters (`effect`, `dependencies`, and `options` with `wait`, `leading`, `trailing`, `maxWait`) and its `void` return type. This section clarifies the purpose and default values for each configurable option. ```APIDOC Parameters: effect: The effect to debounce. dependencies: The dependencies array. options: The options object. wait: The number of seconds to delay. Defaults to `0`. leading: Specify invoking on the leading edge of the timeout. Defaults to `false`. trailing: Specify invoking on the trailing edge of the timeout. Defaults to `true`. maxWait: The maximum time `state` is allowed to be delayed before invoking. Returns: void ``` -------------------------------- ### APIDOC: useDebounceCallback Parameters and Return Values Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-debounce-callback/README.md Detailed API documentation outlining the parameters accepted by `useDebounceCallback`, including the `callback` function and the `options` object with properties like `wait`, `leading`, `trailing`, and `maxWait`. It also describes the structure of the `UseDebounceResult` object returned, which includes `run`, `cancel`, `flush`, and `pending` methods/properties. ```APIDOC Parameters: callback: The function to debounce. options: The options object. wait: The number of seconds to delay. Defaults to 0. leading: Specify invoking on the leading edge of the timeout. Defaults to false. trailing: Specify invoking on the trailing edge of the timeout. Defaults to true. maxWait: The maximum time state is allowed to be delayed before invoking. Returns: A UseDebounceResult object. run: The debounced function. cancel: Cancels any pending invocation. flush: Immediately invokes a pending invocation. pending: Whether there is a pending invocation. ``` -------------------------------- ### APIDOC useAsyncCallback Hook Parameters and Return Values Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async-callback/README.md Comprehensive API documentation for the `useAsyncCallback` hook. It details the `callback` parameter, which is the asynchronous function to be wrapped, and describes the structure of the returned `LuaTuple`, including the `AsyncState` object (with `status`, `value`, `message`) and the executor function. ```APIDOC Parameters: - callback: The async function to call. Returns: - The current state of the async function. - status: The status of the last promise. - value: The value if the promise resolved. - message: The error message if the promise rejected. - A function that calls the async function. ``` -------------------------------- ### useDeferState Hook API Reference: Parameters and Returns Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-defer-state/README.md Details the API of the `useDeferState` hook, describing the `initialState` parameter and the two elements returned: the current stateful value and the function to schedule state updates. ```APIDOC Parameters: - initialState: State used during the initial render. Returns: - A stateful value. - A function which schedules a state update. ``` -------------------------------- ### useEventListener Hook API Documentation Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-event-listener/README.md Detailed API documentation for the `useEventListener` hook, including available options, parameters, and return values. ```APIDOC Options: connected: Whether the listener should be connected. Defaults to true. once: Whether the listener should be disconnected after the first time it is called. Defaults to false. Parameters: event: The event to listen to. listener: The listener to call when the event fires. options: Optional config for the listener. Returns: void ``` -------------------------------- ### useThrottleState Hook API Reference Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-throttle-state/README.md Detailed API documentation for the `useThrottleState` hook, including its TypeScript signature, parameters, and return values. It outlines the configurable options for throttling behavior. ```TypeScript function useThrottleState(initialState: T, options?: UseThrottleOptions): T; ``` ```APIDOC Parameters: - initialState: T - The initial state. - options: UseThrottleOptions (optional) - The options object. - wait: number - The number of seconds to throttle. Defaults to 0. - leading: boolean - Specify invoking on the leading edge of the timeout. Defaults to true. - trailing: boolean - Specify invoking on the trailing edge of the timeout. Defaults to true. Returns: - T - The throttled state. - Function - A function to update the throttled state. ``` -------------------------------- ### useAsyncEffect API Parameters and Returns Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async-effect/README.md Details the parameters required by the `useAsyncEffect` hook and its return type. The `effect` parameter is the asynchronous function to execute, and `deps` is an optional array of dependencies. ```APIDOC Parameters: - effect: The async effect to run. - deps: The dependencies to watch for changes. Returns: - void ``` -------------------------------- ### Document useDeferEffect Hook Parameters (APIDOC) Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-defer-effect/README.md This section documents the parameters for the `useDeferEffect` hook. It specifies the `callback` as the function to execute after rendering and `deps` as an optional array for dependency tracking. ```APIDOC callback - A function to run after the component renders. deps - An array of values that the effect depends on. If any of the values change, the effect will run again. ``` -------------------------------- ### useBindingListener API Reference Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-binding-listener/README.md Detailed API documentation for the `useBindingListener` hook, including its parameters and return type. The hook subscribes a given listener to binding updates, calling it with the current value on mount and whenever the binding changes. The listener is memoized. ```APIDOC useBindingListener: Parameters: binding: The binding to subscribe to. If not a valid binding, the listener is called with the value passed to the hook. listener: The listener to call when the binding updates. This parameter is memoized. Returns: void ``` -------------------------------- ### useInterval Hook API Reference Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-interval/README.md Detailed API documentation for the `useInterval` React hook, outlining its TypeScript signature, parameters, and return value. ```APIDOC function useInterval(callback: () => void, delay?: number, options: UseIntervalOptions): () => void; Parameters: callback: The function to run every `delay` seconds. delay: The number of seconds to wait between each call to `callback`. If `undefined`, the interval is cleared. options: Options for the interval. immediate: If `true`, the callback is called immediately when the interval is set. Defaults to `false`. Returns: A function that clears the interval. ``` -------------------------------- ### APIDOC: useMouse Hook Signature and Details Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-mouse/README.md Documents the `useMouse` React hook, detailing its function signature, parameters, and return type. It provides a binding to the mouse position, optionally calling a listener on mouse movement. ```APIDOC useMouse(listener?: (mouse: Vector2) => void): Binding Description: Returns a binding to the position of the mouse. If a listener is provided, it will be called when the mouse moves and once on mount. Parameters: listener: (mouse: Vector2) => void - An optional listener to be called when the mouse moves. Returns: Binding - The position of the mouse in pixels. ``` -------------------------------- ### useSpring Hook API Reference Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-spring/README.md Defines the API signature for the `useSpring` hook, including its generic type parameters, input arguments, and the type of the returned binding. ```APIDOC function useSpring(goal: T | Binding, options?: SpringOptions): Binding Parameters: goal: T | Binding - The goal of the motor. options: SpringOptions (optional) - Options for the spring (or a spring config). Returns: Binding - A binding of the motor's value. ``` -------------------------------- ### useAsync Hook Return Values (APIDOC) Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async/README.md Describes the three-element tuple returned by the `useAsync` hook, explaining what each element represents (result, status, or error message). ```APIDOC - The result if the promise resolved. - The status of the promise. - The error message if the promise rejected or cancelled. ``` -------------------------------- ### APIDOC: useThrottleEffect Hook Definition Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-throttle-effect/README.md Detailed API documentation for the `useThrottleEffect` hook, outlining its function signature, parameters, and return type. This hook provides throttled execution of effects, configurable with `wait` time and leading/trailing edge options. ```APIDOC useThrottleEffect(effect: () => (() => void) | void, dependencies?: unknown[], options?: UseThrottleOptions): void Parameters: - effect: The effect function to be throttled. - dependencies: An optional array of dependencies for the effect. - options: An optional object to configure throttling behavior. - wait: number (Defaults to 0) - The number of seconds to throttle. - leading: boolean (Defaults to true) - Specify invoking on the leading edge of the timeout. - trailing: boolean (Defaults to true) - Specify invoking on the trailing edge of the timeout. Returns: - void: The hook does not return any value. ``` -------------------------------- ### APIDOC: useMountEffect Hook Definition Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-mount-effect/README.md Provides the API specification for the `useMountEffect` hook, detailing its function signature, parameters, and return type. ```APIDOC useMountEffect(callback: () => void): void Parameters: callback: () => void - The callback to run on mount. Returns: void ``` -------------------------------- ### useKeyPress Hook Return Value Documentation Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-key-press/README.md Describes the boolean value returned by the `useKeyPress` hook, indicating whether any of the specified keys or shortcuts are currently pressed. ```APIDOC boolean - Whether any of the given keys or shortcuts are pressed. ``` -------------------------------- ### TypeScript Signature for useAsyncCallback Hook Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async-callback/README.md Defines the TypeScript type signature for `useAsyncCallback`. It specifies the generic types for the asynchronous callback's return value and arguments, and details the `LuaTuple` return type, which includes the current `AsyncState` and the executor function. ```ts function useAsyncCallback(callback: AsyncCallback): LuaTuple<[AsyncState, AsyncCallback]>; ``` -------------------------------- ### useAsync Hook Signature (TypeScript) Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async/README.md Defines the TypeScript type signature for the `useAsync` hook, specifying its callback function, optional dependencies, and the tuple of values it returns. ```ts function useAsync( callback: () => Promise, deps: unknown[] = [], ): [result?: T, status?: Promise.Status, message?: unknown]; ``` -------------------------------- ### TypeScript Signature for useDeferCallback Hook Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-defer-callback/README.md Defines the type signature for the `useDeferCallback` hook, showing its generic type parameter, the `callback` input, and the returned tuple of `execute` and `cleanup` functions. This signature ensures type safety and clarity for developers using the hook. ```ts function useDeferCallback( callback: (...args: T) => void, ): [execute: (...args: T) => void, cleanup: () => void]; ``` -------------------------------- ### TypeScript useThrottleEffect Function Signature Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-throttle-effect/README.md Defines the TypeScript signature for the `useThrottleEffect` hook, detailing its parameters and return type. This signature outlines how the hook accepts an effect function, an optional dependencies array, and an optional options object for throttling configuration. ```typescript function useThrottleEffect( effect: () => (() => void) | void, dependencies?: unknown[], options?: UseThrottleOptions, ): void; ``` -------------------------------- ### APIDOC: useTimer Hook Parameters and Return Type Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-timer/README.md Details the parameters accepted by the `useTimer` hook and the structure of the `Timer` object it returns. The `Timer` object includes a `value` binding and methods for controlling the timer's state. ```APIDOC Parameters: initialValue: An optional initial value for the timer. Defaults to 0. Returns: A Timer object: value: A binding that will update every frame. start(): Starts the timer if it is not already running. stop(): Stops the timer if it is running. reset(): Resets the value to 0. set(value): Sets the value to a new value. ``` -------------------------------- ### useTagged Hook API Reference Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-tagged/README.md Details the parameters required by the `useTagged` hook and the type of value it returns. ```APIDOC Parameters: - tag: The tag to filter instances for. Returns: - A list of instances with the given tag. ``` -------------------------------- ### useKeyPress Hook TypeScript Signature Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-key-press/README.md Defines the TypeScript signature for the `useKeyPress` hook, detailing its parameters and boolean return type. ```ts function useKeyPress(keyCodes: KeyCodes[], options?: KeyPressOptions): boolean; ``` -------------------------------- ### APIDOC: useLifetime Hook Definition Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-lifetime/README.md API documentation for the `useLifetime` React hook, detailing its signature, parameters, and return type. It provides a time-tracking binding that updates on Heartbeat and can be reset by dependencies. ```APIDOC useLifetime(dependencies?: unknown[]): Binding dependencies: unknown[] (optional) Description: An optional array of dependencies. If provided, the binding will reset to 0 whenever any of the dependencies change. Returns: Binding Description: A binding that will update with the amount of time that has passed since the component mounted. ``` -------------------------------- ### TypeScript useMotion Hook Signature Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-motion/README.md Defines the type signature for the `useMotion` hook, specifying its generic type parameter `T`, the `initialValue` input, and the `LuaTuple` return type containing a `Binding` and a `Motion` object. ```typescript function useMotion(initialValue: T): LuaTuple<[value: Binding, motor: Motion]> ``` -------------------------------- ### useUnmountEffect Hook API Definition Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-unmount-effect/README.md Defines the TypeScript signature, parameters, and return type for the `useUnmountEffect` React hook, detailing its functional contract. ```APIDOC useUnmountEffect: Signature: function useUnmountEffect(callback: () => void): void Parameters: callback: The callback to call when the component unmounts. Returns: void ``` -------------------------------- ### TypeScript Overloads for useDeferState Hook Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-defer-state/README.md Defines the two overloaded signatures for the `useDeferState` hook, illustrating its flexibility for managing state with or without an initial value, and specifying the types for state and its updater function. ```ts function useDeferState(initialState: T | (() => T)): [state: T, setState: Dispatch>]; function useDeferState( initialState?: void, ): [state: T | undefined, setState: Dispatch>]; ``` -------------------------------- ### useCamera Hook Type Signature Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-camera/README.md Defines the type signature for the useCamera hook, indicating it returns a Camera instance. This hook returns the value of Workspace.CurrentCamera and triggers a re-render if the current camera changes. ```tsx function useCamera(): Camera; ``` -------------------------------- ### useThrottleCallback Hook API Definition Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-throttle-callback/README.md Defines the signature, parameters, and return type for the `useThrottleCallback` hook, detailing its generic type, input options, and the structure of the returned `UseDebounceResult` object. ```APIDOC useThrottleCallback(callback: T, options?: UseThrottleOptions): UseDebounceResult Parameters: callback: T - The function to throttle. options?: UseThrottleOptions - The options object. wait: number - The number of seconds to throttle. Defaults to 0. leading: boolean - Specify invoking on the leading edge of the timeout. Defaults to true. trailing: boolean - Specify invoking on the trailing edge of the timeout. Defaults to true. Returns: UseDebounceResult run: Function - The throttled function. cancel: Function - Cancels any pending invocation. flush: Function - Immediately invokes a pending invocation. pending: boolean - Whether there is a pending invocation. ``` -------------------------------- ### TypeScript: useDebounceEffect Hook Signature Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-debounce-effect/README.md Defines the TypeScript signature for the `useDebounceEffect` hook, outlining its required `effect` callback, optional `dependencies` array, and `options` object for configuring debouncing behavior. This signature specifies the types for all inputs and the `void` return type. ```typescript function useDebounceEffect( effect: () => (() => void) | void, dependencies?: unknown[], options?: UseDebounceOptions, ): void; ``` -------------------------------- ### Define useAsyncEffect Hook Signature Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-async-effect/README.md Defines the TypeScript signature for the `useAsyncEffect` hook, showing its parameters and return type. It takes an asynchronous effect function and an optional dependency array. ```typescript function useAsyncEffect(effect: () => Promise, deps?: unknown[]): void; ``` -------------------------------- ### APIDOC: useComposedRef Hook Signature and Details Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-composed-ref/README.md Defines the signature, parameters, and return type for the `useComposedRef` hook. This hook combines multiple ref functions into a single memoized ref, created only once on mount, while still calling the latest refs passed. ```APIDOC useComposedRef(...refs: (RefFunction | undefined)[]): RefFunction Description: Combines multiple ref functions into a single ref function and memoizes the result. To prevent excess ref calls, the composed ref is only created once on mount. It will call the latest refs passed, though, so it is safe to pass in refs that might change. Parameters: refs: An array of ref functions. Returns: A ref function that calls all of the given ref functions. ``` -------------------------------- ### API Reference: useViewport Hook Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-viewport/README.md Documents the `useViewport` React hook, which provides a binding to the current viewport size. It can optionally accept a listener function to be notified of viewport changes. ```APIDOC useViewport(listener?: (viewport: Vector2) => void): Binding Parameters: listener: An optional listener to be called when the viewport size changes. Returns: The size of the viewport in pixels. ``` -------------------------------- ### Define useLatestCallback Hook Type Signature (TypeScript) Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-latest-callback/README.md Specifies the TypeScript type signature for the `useLatestCallback` hook. It takes a generic callback function `T` and returns a memoized version of the same type, ensuring type safety and consistency. ```typescript function useLatestCallback(callback: T): T; ``` -------------------------------- ### useUpdateEffect Hook TypeScript Signature Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-update-effect/README.md This API documentation defines the function signature for `useUpdateEffect`. It specifies that the hook accepts a callback function, which can optionally return a cleanup function, and an optional array of dependencies. The hook itself does not return any value. ```APIDOC function useUpdateEffect(callback: () => void | (() => void), dependencies?: DependencyList): void; ``` -------------------------------- ### Define useBindingListener Hook Signature Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-binding-listener/README.md Defines the TypeScript signature for the `useBindingListener` hook, showing its generic type `T`, the `binding` parameter which can be `T` or `Binding`, and the `listener` callback function that receives the updated value. ```typescript function useBindingListener(binding: T | Binding, listener: (value: T) => void): void; ``` -------------------------------- ### useTimeout Hook API Definition Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-timeout/README.md Defines the signature, parameters, and return type of the `useTimeout` React hook. This hook sets a timeout to execute a callback function after a specified delay, providing a mechanism to clear the timeout. ```APIDOC useTimeout Hook: Signature: function useTimeout(callback: () => void, delay?: number): () => void Description: Sets a timeout that runs the callback after delay seconds. Returns a function that clears the timeout. If delay is undefined, the timeout is cleared. If the delay updates, the timeout is reset. The callback is memoized for you and will not reset the timeout if it changes. Parameters: callback: () => void - The function to run after delay seconds. delay?: number - The number of seconds to wait before calling callback. If undefined, the timeout is cleared. Returns: () => void - A function that clears the timeout. ``` -------------------------------- ### API Definition for useUpdate Hook Source: https://github.com/littensy/pretty-react-hooks/blob/master/src/use-update/README.md Defines the TypeScript signature of the `useUpdate` hook. It specifies that the hook returns a function that takes no arguments and returns void, intended for forcing component updates. ```ts function useUpdate(): () => void; ```