'use client' // State and effects over a loader's lifecycle: the react-server build // has neither. import { useCallback, useEffect, useRef, useState } from 'react' /** * Options for the useRuvyxaLoader hook. */ export interface UseLoaderOptions { /** If false, the loader will not execute automatically. Default: true. */ enabled?: boolean /** Dependencies that trigger a refetch when changed. */ deps?: unknown[] } /** * Result returned by the useRuvyxaLoader hook. */ export interface UseLoaderResult { /** The loaded data, or undefined if still loading or errored. */ data: T | undefined /** Whether the loader is currently fetching. */ loading: boolean /** Error thrown by the loader, if any. */ error: Error | undefined /** Manually trigger a refetch. */ refetch: () => void } /** * React hook for consuming Ruvyxa loaders on the client side. * * Provides loading, error, and data states with automatic refetch support. * Handles race conditions from stale closures and component unmounting. * * Usage: * ```tsx * function UserProfile({ userId }: { userId: string }) { * const { data, loading, error, refetch } = useRuvyxaLoader( * () => fetch(`/api/users/${userId}`).then(r => r.json()), * { deps: [userId] } * ) * * if (loading) return

Loading...

* if (error) return

Error: {error.message}

* return
{data.name}
* } * ``` */ export function useRuvyxaLoader( loader: () => Promise, options: UseLoaderOptions = {}, ): UseLoaderResult { const { enabled = true, deps = [] } = options const [data, setData] = useState(undefined) const [loading, setLoading] = useState(enabled) const [error, setError] = useState(undefined) // Track the current request to handle race conditions const requestIdRef = useRef(0) const mountedRef = useRef(true) // Inline loaders are the documented API. Keep their latest implementation without // treating each render as a request invalidation; `deps` owns automatic refetching. const loaderRef = useRef(loader) loaderRef.current = loader // `deps` is caller-supplied, so its length can change between renders — a // list built from state is the obvious case. Spreading it into the effect's // dependency array would make that array change size, which React rejects // outright ("The final argument passed to useEffect changed size between // renders"). Comparing the array here and exposing a counter keeps the // effect's dependency array a fixed shape while preserving React's own // comparison rule: a refetch happens when any entry stops being `Object.is` // equal to the previous render's entry. const depsRef = useRef(deps) const depsVersionRef = useRef(0) if ( depsRef.current.length !== deps.length || depsRef.current.some((value, index) => !Object.is(value, deps[index])) ) { depsRef.current = deps depsVersionRef.current += 1 } const depsVersion = depsVersionRef.current const execute = useCallback(() => { if (!enabled) { // Disabling the hook must retire an in-flight request. Otherwise its // completion can update state after the caller has disabled loading. requestIdRef.current++ setLoading(false) return } const currentId = ++requestIdRef.current setLoading(true) setError(undefined) // Start through a resolved promise so a loader that throws before returning // its promise follows the same error-state path as an async rejection. Promise.resolve() .then(() => loaderRef.current()) .then((result) => { // Only update state if this is still the latest request and component is mounted if (mountedRef.current && currentId === requestIdRef.current) { setData(result) setLoading(false) } }) .catch((err) => { if (mountedRef.current && currentId === requestIdRef.current) { setError(err instanceof Error ? err : new Error(String(err))) setLoading(false) } }) // eslint-disable-next-line react-hooks/exhaustive-deps }, [enabled]) useEffect(() => { mountedRef.current = true execute() return () => { mountedRef.current = false } // eslint-disable-next-line react-hooks/exhaustive-deps }, [execute, depsVersion]) const refetch = useCallback(() => { execute() }, [execute]) return { data, loading, error, refetch } }