Table of Contents

Class Hooks

Namespace
Velvet
Assembly
Velvet.Docs.dll

Single entry point for all hooks invoked from a [Component] static VNode body. Hooks may only be called during Render(), unconditionally and in a stable order (the Rules of Hooks). For example, UseState<T>(T) returns the 2-tuple (value, setValue) where setValue is a StateUpdater<T> accepting either a replacement value (setValue.Invoke(next)) or a functional updater (setValue.Invoke(prev => next)).

public static class Hooks
Inheritance
object
Hooks

Methods

ForwardedRef<T>()

Retrieves the handle reference passed by the parent via V.Component<TRef>(componentRef:).

UseActionData<T>()

Returns the result of the action that committed the current location, when the action belongs to the route at the current Outlet depth, cast to T: React Router's useActionData. Returns default otherwise.

UseAnimate()

Framer Motion's useAnimate: a scope ref to give the root element (refCallback: scope.SetElement) and an Animator whose Animate animates elements inside it by reference or by selector, alone or as a sequence whose segments overlap through AnimateAt. Each call returns AnimateControls. What it animates are inline values, so it reaches elements outside the declarative Motion tree; the animations run on the mount's frames and are stopped when the component unmounts.

UseAnimationSequence(IReadOnlyList<AnimationSequenceStep>, object?[]?, bool, bool)

Plays an ordered AnimationSequenceStep array over time, exposing the active step's label/transition to feed straight into a coordinator V.Motion(animate:, transition:). Velvet's timeline primitive: the hook owns the clock (via UseFrame(Action<float>, int)) and the step walk, so a caller never hand-rolls UseEffect(Func<Action?>?, object?[]?) plus a timer plus UseState<T>(T) to sequence a multi-stage animation. Descendant V.Motion nodes naming no label of their own inherit the coordinator's label exactly as they already do for any hand-toggled label change; "one at a time" fan-out across a list of such descendants is StaggerChildrenSec on a step's own Transition — there is no separate multi-target API.

UseAnimationSequence(IReadOnlyList<AnimationSequenceStep>, object?[]?, int, bool, float)

Plays steps as the overload taking loop does, a fixed number of times: the Web Animations API's iterations and CSS's animation-iteration-count. Each pass after the first starts at step 0 once the last step's hold elapses, and IsComplete latches when the last pass's last hold elapses, with that pass's last step still current. A gap between passes is repeatDelaySec, Framer Motion's repeatDelay; under loop a trailing Wait(float) step is the same gap, since no completion waits behind it.

UseAsyncError()

Returns the exception the nearest V.Await above the caller is rendering its errorElement for: React Router's useAsyncError. Returns null elsewhere.

UseAsyncValue<T>()

Returns the value the nearest V.Await above the caller resolved, cast to T: React Router's useAsyncValue. Returns default outside one, and beneath one that is rendering its errorElement.

UseBlocker(bool)

Blocks navigation departures while shouldBlock is true, as React Router's useBlocker(boolean) does. The component re-renders whenever the returned Blocker's state changes. Must be used inside Render() only.

UseBlocker(Func<BlockerFunctionArgs, bool>)

Conditionally blocks navigation departures, handing the Blocker the predicate of every render so it answers with the state the latest render captured. The component re-renders whenever the returned Blocker's state changes. Must be used inside Render() only.

UseBlocker(Func<BlockerFunctionArgs, bool>, params object?[]?)

Conditionally blocks navigation departures, handing the Blocker a render's predicate only when a dependency changes. The component re-renders whenever the returned Blocker's state changes. Must be used inside Render() only.

UseCallback(Action)

Unmemoized UseCallback<T>(T) for a callback of type Action.

UseCallback(Action, params object?[]?)

Memoized UseCallback<T>(T, params object?[]?) for a callback of type Action.

UseCallback<T>(T)

Returns the latest callback every render without memoization. With no deps argument the callback behaves as identity — a fresh closure each render. Use this overload only when you intentionally want the unmemoized form (e.g. handler that already captures no render-scoped state). For memoized stable references prefer the UseCallback<T>(T, params object?[]?) overload with an explicit deps array.

UseCallback<T>(T, params object?[]?)

Returns the same delegate reference as long as the dependency array is unchanged.

UseCallback<T1, T2>(Action<T1, T2>)

Unmemoized UseCallback<T>(T) for a callback of type Action<T1, T2>.

UseCallback<T1, T2>(Action<T1, T2>, params object?[]?)

Memoized UseCallback<T>(T, params object?[]?) for a callback of type Action<T1, T2>.

UseCallback<T1, TResult>(Func<T1, TResult>)

Unmemoized UseCallback<T>(T) for a callback of type Func<T1, TResult>.

UseCallback<T1, TResult>(Func<T1, TResult>, params object?[]?)

Memoized UseCallback<T>(T, params object?[]?) for a callback of type Func<T1, TResult>.

UseCallback<T1, T2, T3>(Action<T1, T2, T3>)

Unmemoized UseCallback<T>(T) for a callback of type Action<T1, T2, T3>.

UseCallback<T1, T2, T3>(Action<T1, T2, T3>, params object?[]?)

Memoized UseCallback<T>(T, params object?[]?) for a callback of type Action<T1, T2, T3>.

UseCallback<T1, T2, TResult>(Func<T1, T2, TResult>)

Unmemoized UseCallback<T>(T) for a callback of type Func<T1, T2, TResult>.

UseCallback<T1, T2, TResult>(Func<T1, T2, TResult>, params object?[]?)

Memoized UseCallback<T>(T, params object?[]?) for a callback of type Func<T1, T2, TResult>.

UseCallback<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult>)

Unmemoized UseCallback<T>(T) for a callback of type Func<T1, T2, T3, TResult>.

UseCallback<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult>, params object?[]?)

Memoized UseCallback<T>(T, params object?[]?) for a callback of type Func<T1, T2, T3, TResult>.

UseContext<T>(ComponentContext<T>)

Reads the value of the given context from the nearest Provider. Returns the context's default value when no Provider is present.

UseDeferredValue<T>(T)

Defers commits of value changes through the Transition lane and returns the previous value during urgent re-renders. Use this to deprioritize heavy re-render inputs such as search queries.

UseDeferredValue<T>(T, T)

Overload taking an initialValue. On the initial render the hook returns initialValue instead of value and immediately schedules a Transition-lane re-render that defers toward value. Subsequent renders behave exactly like UseDeferredValue<T>(T).

UseDndContext()

Returns the drag the nearest V.DndContext holds — dnd-kit's useDndContext. The component re-renders when the active draggable, the target it is over, the collision ranking or the active rect changes. Returns Idle under no V.DndContext, including under a scope declared only through DndContext.

UseDndMonitor(DndMonitorListener)

Registers listener with the nearest V.DndContext while the component is mounted — dnd-kit's useDndMonitor. Each callback runs after the context's own callback of the same name; the one a render passes is the one called, without registering again.

UseDraggable(string)

Returns the drag state of the draggable id names under the nearest V.DndContext — dnd-kit's useDraggable, read-only: the element still carries V.Draggable or the Draggable slot. The component re-renders when the active draggable or the target it is over changes, and on every move while this draggable is the one dragged, for Transform.

UseDroppable(string)

Returns the drag state of the droppable id names under the nearest V.DndContext — dnd-kit's useDroppable, read-only: the element still carries V.Droppable or the Droppable slot. The component re-renders when the active draggable or the target it is over changes.

UseEffect(Func<Action?>?, object?[]?)

Position-based asynchronous effect. Runs at the next frame boundary, after the frame is painted.

UseEffect(Func<IDisposable>, object?[]?)

IDisposable variant.

UseErrorBoundary()

Gives a component below an error boundary that boundary's reset and a way to make it catch an error — react-error-boundary's useErrorBoundary().

UseErrorBoundaryReset(object?[]?, Action<ErrorBoundaryResetDetails>?)

Lets an error boundary that has caught render its children again: react-error-boundary's resetErrorBoundary as the returned ErrorBoundaryReset, its resetKeys as resetKeys and its onReset as onReset. Call it inside Render() of an [Component(IsErrorBoundary = true)] component.

UseFallback(Func<Exception, ErrorInfo, VNode>)

Two-argument fallback factory variant that receives the caught exception and an ErrorInfo with the throwing fiber's ComponentStack, describing where the error was caught.

UseFallback(Func<Exception, VNode>)

Registers a fallback factory inside Render() of an [Component(IsErrorBoundary = true)] component. When this component catches a Render exception from a child, the registered factory is invoked to produce the fallback VNode. This API expresses, in functional Velvet, the Error Boundary pattern of returning a fallback when a descendant render throws. Must be called during Render since it is overwritten on every render.

UseFocusManager()

Returns the FocusManager of the focus scope around this component — React Aria's useFocusManager. The manager is reference-stable across renders and resolves the scope each time a method is called, so call its methods from an event handler or an effect, not during render.

UseFocusRing()

Exposes an element's focus state — and specifically keyboard/gamepad-visible focus, as distinct from pointer focus — as re-rendering component state. Pass Ref as the target element's refCallback:. For pure styling, the focus-visible: class variant already covers the same distinction without a hook — reach for this when the component must RENDER differently (e.g. a "press A to select" hint), not just restyle.

When composing Ref with other per-element work in one callback, wrap the composed lambda in Hooks.UseCallback: a per-render lambda is a fresh identity each render, so every patch would cycle the ref (cleanup on a still-focused element, then re-setup) — the same re-render feedback an inline ref that writes state on every render would produce.

UseFrame(Action<float>, int)

Per-frame callback: onFrame runs once per frame with the elapsed time in seconds while the component stays mounted, and stops on unmount. The latest render's closure is always the one invoked — a re-render swaps the callback without re-subscribing — so per-frame data flows without touching component state (the escape hatch for simulation-driven visuals; setting state per frame would re-render the world every tick). Frames tick while the component's host is attached to a panel and pause while it is not. The elapsed time is measured on the mount's MotionClock, and a frame over which that clock did not move invokes nothing. priority orders callbacks within the SAME panel — lower runs earlier, equal priorities run in subscription (mount) order, and this stays true across a keyed reorder of the host. A positive priority also takes rendering over, as in react-three-fiber: while the host is attached, a SceneView(Camera?, string?, string?, string?, float, StyleOverrides?, Func<VisualElement, Action>?, string?, string?, string?, IReadOnlyDictionary<string, string>?, IReadOnlyDictionary<string, string>?, FiberEventBinding[]?) showing its camera in the same panel holds that camera disabled, and the callback renders it with Camera.Render(). The latest render's priority applies live, the same way onFrame does — changing it does not restart the subscription or move it among same-priority siblings.

UseHref(string, RelativeRoutingType)

Returns the string an anchor would link to with, its resolved pathname, search and hash joined: React Router's useHref.

UseId(string?)

Returns a stable unique ID string tied to the component instance and slot position. Re-renders of the same component return the same ID; different instances or different slots receive different IDs. Use as a unique key for label-to-field association or aria attributes.

UseImperativeHandle<THandle>(Ref<THandle>, Func<THandle>)

Builds a public handle (via factory) and stores it into the Ref<T> the parent passed via componentRef:. This no-deps overload re-invokes the factory every render (equivalent to passing null as deps); it exists so omitting deps is unambiguous — the params object[] overload would otherwise observe an empty array (not null) and incorrectly freeze the handle to the first render.

UseImperativeHandle<THandle>(Ref<THandle>, Func<THandle>, params object?[]?)

Builds a handle via factory and stores it into the parent-supplied Ref<T>, rebuilding only when deps change (compared with Object.is semantics).

UseInRouterContext()

True when a V.RouterProvider is mounted above the caller: React Router's useInRouterContext.

UseInsertionEffect(Func<Action?>?, object?[]?)

Position-based insertion effect. Runs synchronously after Render completes and before any UseLayoutEffect(Func<Action?>?, object?[]?) of the same commit. Intended for injecting styles: the DOM is not yet laid out, so the body must not read layout or refs — use UseLayoutEffect(Func<Action?>?, object?[]?) for that.

UseInsertionEffect(Func<IDisposable>, object?[]?)

IDisposable variant. Dispose() is called when deps change.

UseLayoutEffect(Func<Action?>?, object?[]?)

Position-based layout effect. Runs synchronously immediately after Render completes, before the frame is painted, with the committed tree laid out: layout, resolvedStyle and worldBound read here reflect this commit. A state update made here re-renders before the frame is painted.

UseLayoutEffect(Func<IDisposable>, object?[]?)

IDisposable variant. Dispose() is called when deps change.

UseLoaderData<T>()

Returns the loader data for the route at the current Outlet depth, cast to T. Returns default when there is no data.

UseLocation()

Returns the current router location. Reads Location; returns null until the router publishes its first location.

UseMatch(string)

Returns the match for the given pattern against the current location, or null when it does not match. The pattern uses the same segment syntax as routes (literal / :param / *); matching is case-insensitive.

UseMatches()

Returns every route matched by the current location, parent first, each with the loader data and Handle it carries: React Router's useMatches.

UseMemo<T>(Func<T>)

Recomputes factory on every render (no memoization). With no deps argument the value is never cached — prefer the UseMemo<T>(Func<T>, params object?[]?) overload with an explicit deps array to reuse the value while the dependencies are unchanged.

UseMemo<T>(Func<T>, params object?[]?)

Returns the same computed value as long as the dependency array is unchanged; recomputes factory only when a dependency changes.

UseMutableRef<T>(Func<T>)

Variant of UseMutableRef<T>(T) that takes a lazy factory. initialFactory is invoked only on the first render to seed Current; subsequent renders return the same instance without invoking the factory.

UseMutableRef<T>(T)

Hook that returns the same MutableRef<T> across re-renders, used as an instance-scoped mutable slot. Unlike UseRef<T>(), the type parameter is unconstrained so value types can be stored directly. On the first render, allocates new MutableRef<T>(initial) and stores it in the fiber slot; subsequent renders return the same instance. Writes to Current do not schedule a re-render.

UseMutation(MutationOptions)

No-input void overload of UseMutation<TVariables, TData>(MutationOptions<TVariables, TData>). Use when the mutation takes no input and returns no data. Pair with Mutate<TData>(MutationResult<Unit, TData>) to call mutation.Mutate() without an explicit Unit.Default argument.

UseMutation<TVariables>(MutationOptions<TVariables>)

Void-return overload of UseMutation<TVariables, TData>(MutationOptions<TVariables, TData>). Use when the mutation function returns no data (typical for Store-action mutations where state is updated internally).

UseMutation<TVariables, TData>(MutationOptions<TVariables, TData>)

Returns a handle that tracks the lifecycle (Idle / Pending / Success / Error) of an async mutation. The caller invokes Mutate / MutateAsync with TVariables; the MutationFn runs and the handle's status / data / error fields are updated, triggering a re-render.

UseMutation<TVariables, TData, TContext>(MutationOptions<TVariables, TData, TContext>)

Context-carrying overload of UseMutation<TVariables, TData>(MutationOptions<TVariables, TData>), TanStack Query's onMutate form: OnMutate runs before the mutation function, and its return value is the context that call's OnSuccess / OnError / OnSettled receive.

UseNavigate()

Returns React Router's navigate: navigate(to, options) pushes (or, with Replace, replaces) the target path, and navigate(delta) moves along the history stack. The target may be absolute (/foo) or relative (., .., ../sibling). Relative targets resolve from the calling component's enclosing Outlet route level. Without one, the router uses the current leaf route level when matches exist; otherwise it uses the current URL path, or the root before the first location. Relative set to Path drops URL segments of that route's pathname instead of whole routes. Navigation is driven by the router V.RouterProvider publishes above the caller.

UseNavigation()

Returns Navigation of the Router V.RouterProvider publishes above the caller, and re-renders the component as it changes.

UseNavigationType()

Returns how the current location was reached, and re-renders the component as the location changes: React Router's useNavigationType.

UseOptimistic<TState, TAction>(TState, Func<TState, TAction, TState>)

Returns the optimistic state and an addOptimistic action. With no optimistic update outstanding the returned state is passthroughState. Each addOptimistic(action) records an entry and requests a render, and every render returns passthroughState folded through the outstanding entries by applyOptimistic, in the order they were added — so an entry lands on whatever the authoritative state has become while it is outstanding. An entry added inside a startTransition callback belongs to the innermost transition open there whose isPending is lit, and is discarded when that transition settles (or, with an async action in flight, when none is left), whether or not passthroughState changed and whether the action succeeded or faulted; one transition settling leaves another's entries in place. An entry added where no such transition is open, while an async action is in flight, belongs to the actions in flight together. As in React, the actions in flight are entangled: a transition that settles while any is in flight hands its entries to them, so they are discarded once none is left. An action counts from its start until its task completes, whether or not the component that started it is still mounted, so one awaiting a task that never completes holds every later entry. A component rendered by the Transition-lane drain that lands the last work a transition queued leaves that transition's entries out of that render, and a component holding them that the drain did not render that way is rendered without them before that commit's layout effects run. An entry no render has shown when its owner settles is shown once first. An entry nothing owns is discarded by the component's next Transition-lane render.

UseOutletContext<T>()

Returns the context value supplied by the enclosing Outlet. Returns default when no context was supplied.

UseParams()

Returns the path parameters captured for the current location (cumulative across the matched route chain). Returns an empty dictionary when no router is mounted or no parameters were captured.

UseQuery<T>(QueryOptions<T>, QueryClient?)

UseQuery<TQueryFnData, TData>(QueryOptions<TQueryFnData, TData>, QueryClient?) for a query whose result holds the data its query function returns.

UseQuery<TQueryFnData, TData>(QueryOptions<TQueryFnData, TData>, QueryClient?)

TanStack Query's useQuery. Reads the entry options' key names in a QueryClient, fetches it with the options' query function when it has no data or its data is stale, and re-renders the component when a property of the result it reads changes. Components reading one key share one entry and one request in flight, and the entry keeps its result after they unmount, so a component mounting over it later renders that result at once.

UseReducer<TState, TAction>(Func<TState, TAction, TState>, TState)

Local state hook that derives the next state from the current state and a dispatched action.

UseReducer<TArg, TState, TAction>(Func<TState, TAction, TState>, TArg, Func<TArg, TState>)

Lazy-initialized variant taking an init function to compute the initial state. init is invoked exactly once with initialArg on the first render to produce the initial state, then never called again. Use this to defer expensive initialization (large arrays, dictionaries, etc.) so that it does not run on every render.

UseRef<T>()

Hook that returns the same Ref<T> across re-renders. On the first render, creates a new Ref<T>(), stores it in the fiber slot, and returns the same reference at the same position thereafter. Current stays null until it is assigned externally.

UseRef<T>(Func<T>?)

Variant of UseRef<T>() that takes an initial factory. On the first render, invokes initialFactory and stores the result into Current, seeding the ref with a lazily-constructed value.

UseResolvedPath(string, RelativeRoutingType)

Resolves to to an absolute pathname, search and hash as UseNavigate would navigate to it from the calling component's route: React Router's useResolvedPath.

UseRouteError()

Returns the error the route at the current Outlet depth failed with — an error thrown below its element, while rendering, from an effect or from an element callback, or else its loader's — or null when the route did not error.

UseRouteLoaderData<T>(string)

Returns the loader data of the route with the given Id (or RouteId) among the current location's matches, cast to T, from any component beneath the provider: React Router's useRouteLoaderData. Returns default when that route has no data or is not matched.

UseSearchParams()

Returns the parsed query string of the current location together with a setter that navigates to the same path with a new query string.

UseService<T>()

Resolves a service from the IHookServiceResolver provided through Ref. A service-locator hook that reads the host resolver from context, keeping the lookup DI-framework-neutral.

UseSortable(string)

Returns the sorting state of the item id names in the nearest V.SortableContext — dnd-kit's useSortable, read-only: the element is V.Sortable, which moves the items aside itself. The component re-renders when the context's items, the active draggable or the target it is over changes. Outside a V.SortableContext every index is -1 and the items are empty.

UseState<T>(Func<T>)

Lazy-initialized variant taking a factory invoked once for the initial value. initialFactory is invoked exactly once on the first render to produce the initial state; subsequent renders skip the call. Use this when constructing the initial value is expensive (large Map/Set/List allocation, etc.) so the cost is not paid on every render.

UseState<T>(T)

Local state hook. Must be used inside Render() only. Returns the 2-tuple shape (value, setValue) where setValue is a single StateUpdater<T> that accepts either a replacement value or a functional updater.

UseStore<TStore, TSel>(Store<TStore>, Func<TStore, TSel>, IEqualityComparer<TSel>?)

Subscribes to an external Store via a selector. Must be used inside Render() only. The subscription is made in the passive effects of the commit, as UseSyncExternalStore<T>(Func<Action, Action>, Func<T>) makes its own, so a render that throws or suspends subscribes nothing; a change the store makes between the render and the subscription re-renders the component once it is made. A change re-renders it as a UseSyncExternalStore<T>(Func<Action, Action>, Func<T>) notification does: on the Urgent lane, inside a transition as well.

UseSubmit()

Returns a function that submits form data to a route's action, or with a get method navigates with it as the query string: React Router's useSubmit. With no Action it submits to the route the calling component renders in, and a relative one resolves from there; SubmitAsync(object?, SubmitOptions?, CancellationToken) states the rest. The function keeps its identity across renders while the router and that route do.

UseSyncExternalStore<T>(Func<Action, Action>, Func<T>)

Subscribes to a store Velvet does not own and returns its current snapshot — the counterpart of React's useSyncExternalStore(subscribe, getSnapshot). Must be used inside Render() only.

UseTransition()

Returns the pending state and starter for low-priority updates.

Use<T>(Func<CancellationToken, VelvetTask<T>>, object?)

CancellationToken-aware variant of Use<T>(Func<VelvetTask<T>>, object?). The token is cancelled when the resource is superseded (a new key) or the component unmounts; loader implementations are responsible for honoring it and aborting. A resource a transition's render started is not superseded by a render of another lane that presents the old key: it is kept, and cancelled only when a later transition presents a different key, or on unmount.

Use<T>(Func<VelvetTask<T>>, object?)

Declaratively fetches asynchronous data; while pending, throws a Velvet.FiberSuspendSignal to delegate the fallback to the nearest Suspense Boundary.