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:).

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

Conditionally blocks navigation departures (synchronous variant). Must be used inside Render() only.

UseBlocker(Func<NavigationAttempt, CancellationToken, UniTask<bool>>, params object?[])

Conditionally blocks navigation departures (asynchronous variant). Use when integrating with asynchronous UI such as confirmation dialogs.

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.

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).

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.

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.

UseFrame(Action<float>)

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.

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).

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.

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 when no router is mounted.

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.

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.

UseNavigate(bool)

Returns a navigate function that pushes (or, when replace is true, replaces) the given target path. The target may be absolute (/foo) or relative (., .., ../sibling) — relative targets resolve against CurrentLocation. Navigation is driven by Current.

UseNavigation()

Returns the current navigation state. The state is Loading while the active Router is matching or loading the next location, and Idle otherwise. The component re-renders as the router's status transitions.

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

Returns the optimistic state and an addOptimistic action. Normally the returned state equals passthroughState. When addOptimistic(action) is invoked, applyOptimistic derives an optimistic state that is shown immediately (a re-render is requested) while the real update is in flight; once passthroughState changes (the real update lands), the optimistic override is discarded and the pass-through state is shown again.

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.

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.

UseRouteError()

Returns the loader error for the route at the current Outlet depth, or null when the route did not error.

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.

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.

UseTransition()

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

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

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

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

CancellationToken-aware variant of Use<T>(Func<UniTask<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.