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
-
objectHooks
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'suseActionData. Returnsdefaultotherwise.
- UseAnimate()
Framer Motion's
useAnimate: ascoperef to give the root element (refCallback: scope.SetElement) and an Animator whoseAnimateanimates 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. DescendantV.Motionnodes 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 isStaggerChildrenSecon a step's own Transition — there is no separate multi-target API.
- UseAnimationSequence(IReadOnlyList<AnimationSequenceStep>, object?[]?, int, bool, float)
Plays
stepsas the overload takingloopdoes, a fixed number of times: the Web Animations API'siterationsand CSS'sanimation-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 isrepeatDelaySec, Framer Motion'srepeatDelay; underloopa trailing Wait(float) step is the same gap, since no completion waits behind it.
- UseAsyncError()
Returns the exception the nearest
V.Awaitabove the caller is rendering itserrorElementfor: React Router'suseAsyncError. Returns null elsewhere.
- UseAsyncValue<T>()
Returns the value the nearest
V.Awaitabove the caller resolved, cast toT: React Router'suseAsyncValue. Returnsdefaultoutside one, and beneath one that is rendering itserrorElement.
- UseBlocker(bool)
Blocks navigation departures while
shouldBlockis true, as React Router'suseBlocker(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
valuechanges 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 returnsinitialValueinstead ofvalueand immediately schedules a Transition-lane re-render that defers towardvalue. Subsequent renders behave exactly like UseDeferredValue<T>(T).
- UseDndContext()
Returns the drag the nearest
V.DndContextholds — dnd-kit'suseDndContext. The component re-renders when the active draggable, the target it is over, the collision ranking or the active rect changes. Returns Idle under noV.DndContext, including under a scope declared only through DndContext.
- UseDndMonitor(DndMonitorListener)
Registers
listenerwith the nearestV.DndContextwhile the component is mounted — dnd-kit'suseDndMonitor. 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
idnames under the nearestV.DndContext— dnd-kit'suseDraggable, read-only: the element still carriesV.Draggableor 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
idnames under the nearestV.DndContext— dnd-kit'suseDroppable, read-only: the element still carriesV.Droppableor 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
resetErrorBoundaryas the returned ErrorBoundaryReset, itsresetKeysasresetKeysand itsonResetasonReset. 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, thefocus-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:
onFrameruns 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.priorityorders 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 withCamera.Render(). The latest render's priority applies live, the same wayonFramedoes — changing it does not restart the subscription or move it among same-priority siblings.
- UseHref(string, RelativeRoutingType)
Returns the string an anchor would link
towith, its resolved pathname, search and hash joined: React Router'suseHref.
- 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 viacomponentRef:. This no-deps overload re-invokes the factory every render (equivalent to passingnullas deps); it exists so omitting deps is unambiguous — theparams object[]overload would otherwise observe an empty array (notnull) and incorrectly freeze the handle to the first render.
- UseImperativeHandle<THandle>(Ref<THandle>, Func<THandle>, params object?[]?)
Builds a handle via
factoryand stores it into the parent-supplied Ref<T>, rebuilding only whendepschange (compared withObject.issemantics).
- UseInRouterContext()
True when a
V.RouterProvideris mounted above the caller: React Router'suseInRouterContext.
- 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,resolvedStyleandworldBoundread 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. Returnsdefaultwhen 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
patternagainst 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
factoryon 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
factoryonly when a dependency changes.
- UseMutableRef<T>(Func<T>)
Variant of UseMutableRef<T>(T) that takes a lazy factory.
initialFactoryis 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 explicitUnit.Defaultargument.
- 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/MutateAsyncwithTVariables; 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
onMutateform: OnMutate runs before the mutation function, and its return value is the context that call'sOnSuccess/OnError/OnSettledreceive.
- UseNavigate()
Returns React Router's
navigate:navigate(to, options)pushes (or, with Replace, replaces) the target path, andnavigate(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 routerV.RouterProviderpublishes above the caller.
- UseNavigation()
Returns Navigation of the Router
V.RouterProviderpublishes 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
addOptimisticaction. With no optimistic update outstanding the returned state ispassthroughState. EachaddOptimistic(action)records an entry and requests a render, and every render returnspassthroughStatefolded through the outstanding entries byapplyOptimistic, 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 astartTransitioncallback belongs to the innermost transition open there whoseisPendingis lit, and is discarded when that transition settles (or, with an async action in flight, when none is left), whether or notpassthroughStatechanged 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. Returnsdefaultwhen 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 entryoptions' 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
initfunction to compute the initial state.initis invoked exactly once withinitialArgon 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
initialFactoryand stores the result into Current, seeding the ref with a lazily-constructed value.
- UseResolvedPath(string, RelativeRoutingType)
Resolves
toto an absolute pathname, search and hash asUseNavigatewould navigate to it from the calling component's route: React Router'suseResolvedPath.
- 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'suseRouteLoaderData. Returnsdefaultwhen 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
idnames in the nearestV.SortableContext— dnd-kit'suseSortable, read-only: the element isV.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 aV.SortableContextevery index is -1 and the items are empty.
- UseState<T>(Func<T>)
Lazy-initialized variant taking a factory invoked once for the initial value.
initialFactoryis 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)wheresetValueis 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
getmethod navigates with it as the query string: React Router'suseSubmit. 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.