jaspr_hooks library

Ordered lifecycle and state hooks for native Jaspr components.

Classes

AsyncAction<StateT, InputT>
A stable controller for user-initiated asynchronous state changes.
CounterController
Mutable integer state returned by useCounter.
GuardedValueNotifier<T>
A ValueNotifier that ignores assignments after it has been disposed.
Hook<R>
Immutable configuration for a reusable piece of lifecycle-aware state.
HookBuilder
A hook component that delegates its build to builder.
HookComponent
A stateless Jaspr component whose build method may call hooks.
HookState<R, H extends Hook<R>>
Mutable lifecycle state associated with one Hook invocation.
ListController<T>
Mutable list state returned by useList.
MapController<K, V>
Mutable map state returned by useMap.
ObjectRef<T>
A mutable reference whose value survives component rebuilds.
OptimisticState<StateT, UpdateT>
A stable controller for optimistic state layered over authoritative state.
OptimisticUpdateHandle<StateT>
A handle for one pending optimistic update.
QueueController<T>
Mutable first-in, first-out state returned by useQueue.
SetController<T>
Mutable set state returned by useSet.
StableEventCallback<T, R>
A stable callable that always invokes the latest handler supplied to useEvent.
StatefulHookComponent
A stateful Jaspr component whose State.build method may call hooks.
Store<StateT, ActionT>
A mutable state store updated through actions.
ToggleController
Mutable boolean state returned by useToggle.

Enums

ActionConcurrency
Determines how an AsyncAction handles overlapping dispatches.
DocumentVisibility
Whether the browser document is currently visible.
MediaQueryMatch
Whether the browser currently matches a CSS media query.
PreferredColorScheme
The browser's preferred light or dark color scheme.
PreferredMotion
The browser's preferred animation and transition behavior.

Functions

use<R>(Hook<R> hook) → R
Registers hook in the currently building hook component and returns its value.
useAsyncAction<StateT, InputT>({required StateT initialState, required AsyncActionHandler<StateT, InputT> action, ActionConcurrency concurrency = ActionConcurrency.sequential}) AsyncAction<StateT, InputT>
Creates a stable controller for user-initiated asynchronous work.
useBrowserRoute<T>(T serverRoute, T resolve(Uri location), {void onLocationChange(Uri location)?}) → T
Derives a route value from the browser location.
useCallback<T extends Function>(T callback, [List<Object?> keys = const <Object>[]]) → T
Preserves callback until one of keys changes.
useContext() → BuildContext
Returns the BuildContext of the currently building hook component.
useCounter([int initialValue = 0]) CounterController
Creates stable integer state with increment, decrement, and reset operations.
useDebounced<T>(T value, Duration timeout) → T?
Returns value after it has remained unchanged for timeout.
useDisposable<T>(T create(), void dispose(T value), [List<Object?> keys = const <Object?>[]]) → T
Creates an owned resource and disposes it when keys change or its hook is removed.
useDocumentVisibility() DocumentVisibility
Returns the document visibility state.
useEffect(Dispose? effect(), [List<Object?>? keys]) → void
Runs a synchronous browser-client side effect.
useEffectOnce(Dispose? effect()) → void
Runs effect during the hook's first browser-client build.
useEvent<T, R>(R handler(T value)) StableEventCallback<T, R>
Returns a stable callback that always invokes the latest handler.
useExternalStore<T>(ExternalStoreSubscribe subscribe, T getSnapshot(), {T getServerSnapshot()?, ExternalStoreSnapshotEquals<T>? equals}) → T
Reads and subscribes to an external immutable snapshot.
useFuture<T>(Future<T>? future, {T? initialData, bool preserveState = true}) → AsyncSnapshot<T>
Subscribes to future on the browser client and returns its latest snapshot.
useGuardedState<T>(T initialData) GuardedValueNotifier<T>
Creates a GuardedValueNotifier that rebuilds its owning component when changed and silently drops assignments made after the component unmounts.
useId({String prefix = 'jh'}) String
Returns an HTML id that is stable across rebuilds, server rendering, and hydration when the component tree and hook order match.
useImperativeHandle<T extends Object>(ObjectRef<T?>? target, T createHandle(), [List<Object?>? keys]) → void
Exposes a generated handle through target until this hook is replaced or removed.
useInherited<T extends InheritedComponent>({Object? aspect}) → T?
Reads and subscribes to the nearest Jaspr inherited component of type T.
useInterval(VoidCallback callback, Duration? interval, {bool immediate = false}) → void
Repeatedly invokes the latest callback every interval on the browser client.
useIsMounted() IsMounted
Returns a stable callback that becomes false after hook disposal.
useLatest<T>(T value) ObjectRef<T>
Keeps the latest value in a stable reference without requesting rebuilds.
useList<T>([Iterable<T> initialValue = const <Never>[]]) ListController<T>
Creates stable list state initialized with a snapshot of initialValue.
useListenable<T extends Listenable?>(T listenable) → T
Returns listenable and rebuilds when it notifies on the browser client.
useListenableSelector<R>(Listenable? listenable, R selector()) → R
Rebuilds only when the result of selector changes.
useLocation() Uri?
Returns the current document location.
useMap<K, V>([Map<K, V> initialValue = const <Never, Never>{}]) MapController<K, V>
Creates stable map state initialized with a snapshot of initialValue.
useMediaQuery(String query) MediaQueryMatch
Returns whether the document matches query.
useMemoized<T>(T valueBuilder(), [List<Object?> keys = const <Object>[]]) → T
Evaluates valueBuilder once and caches its value until keys change.
useMount(VoidCallback effect) → void
Runs effect during the hook's first browser-client build.
useOnDocumentVisibilityChange(DocumentVisibilityCallback callback) → void
Calls callback when document visibility changes after initial browser synchronization.
useOnListenableChange(Listenable? listenable, VoidCallback listener) → void
Invokes listener when listenable notifies on the browser client.
useOnMediaQueryChange(String query, MediaQueryCallback callback) → void
Calls callback when query changes after initial browser synchronization.
useOnPreferredColorSchemeChange(PreferredColorSchemeCallback callback) → void
Calls callback when the preferred scheme changes after initial browser synchronization.
useOnPreferredMotionChange(PreferredMotionCallback callback) → void
Calls callback when the browser's preferred motion behavior changes.
useOnStreamChange<T>(Stream<T>? stream, {void onData(T event)?, void onError(Object error, StackTrace stackTrace)?, void onDone()?, bool? cancelOnError}) StreamSubscription<T>?
Listens to stream on the browser client and invokes the latest callbacks.
useOnWindowFocus(void callback(), {bool includeVisibilityChange = true}) → void
Calls callback when the window regains focus.
useOptimistic<StateT, UpdateT>(StateT authoritativeState, StateT reducer(StateT current, UpdateT update)) OptimisticState<StateT, UpdateT>
Layers optimistic updates over authoritativeState.
usePostFrameEffect(Dispose? effect(), [List<Object?>? keys]) → void
Runs effect after the next completed browser-client frame.
usePostFrameUpdateEffect(Dispose? effect(), [List<Object?>? keys]) → void
Runs effect after a completed browser frame for updates, skipping the frame that mounted the hook.
usePreferredColorScheme() PreferredColorScheme
Returns the browser's preferred color scheme.
usePreferredMotion() PreferredMotion
Returns the browser's preferred animation and transition behavior.
usePrevious<T>(T value) → T?
Returns the value supplied during the preceding build, or null initially.
useQueue<T>([Iterable<T> initialValue = const <Never>[]]) QueueController<T>
Creates stable queue state initialized with a snapshot of initialValue.
useReducer<StateT, ActionT>(Reducer<StateT, ActionT> reducer, {required StateT initialState, required ActionT initialAction}) Store<StateT, ActionT>
Creates a reducer-backed Store.
useRef<T>(T initialValue) ObjectRef<T>
Preserves a mutable ObjectRef across builds.
useSet<T>([Iterable<T> initialValue = const <Never>[]]) SetController<T>
Creates stable set state initialized with a snapshot of initialValue.
useState<T>(T initialData) → ValueNotifier<T>
Creates a ValueNotifier that rebuilds its owning component when changed.
useStream<T>(Stream<T>? stream, {T? initialData, bool preserveState = true}) → AsyncSnapshot<T>
Subscribes to stream on the browser client and returns its latest snapshot.
useStreamController<T>({bool sync = false, VoidCallback? onListen, VoidCallback? onCancel, List<Object?>? keys}) StreamController<T>
Creates a broadcast StreamController and closes it on hook disposal.
useTimeout(VoidCallback callback, Duration? delay) → void
Invokes the latest callback once after delay on the browser client.
useToggle([bool initialValue = false]) ToggleController
Creates stable boolean state with toggle and reset operations.
useUnmount(VoidCallback effect) → void
Runs effect when the hook is removed from a browser-client component.
useUpdateEffect(Dispose? effect(), [List<Object?>? keys]) → void
Runs effect during updates while skipping the initial client build.
useValueChanged<T, R>(T value, R? valueChange(T oldValue, R? oldResult)) → R?
Calls valueChange when value changes and returns its latest result.
useValueListenable<T>(ValueListenable<T> valueListenable) → T
Subscribes to valueListenable and returns its current value.
useValueNotifier<T>(T initialData, [List<Object?>? keys]) → ValueNotifier<T>
Creates a ValueNotifier and disposes it when its hook is removed.

Typedefs

AsyncActionHandler<StateT, InputT> = FutureOr<StateT> Function(StateT previousState, InputT input)
Computes the next state for an asynchronous action.
Dispose = void Function()
A cleanup function returned by an effect.
DocumentVisibilityCallback = void Function(DocumentVisibility previous, DocumentVisibility current)
Callback invoked after an established document visibility value changes.
ExternalStoreSnapshotEquals<T> = bool Function(T previous, T current)
Decides whether two external-store snapshots represent the same value.
ExternalStoreSubscribe = Dispose Function(VoidCallback notify)
Subscribes notify to an external store and returns its unsubscribe callback.
IsMounted = bool Function()
Function that reports whether its hook remains mounted.
MediaQueryCallback = void Function(MediaQueryMatch previous, MediaQueryMatch current)
Callback invoked after an established media-query result changes.
PreferredColorSchemeCallback = void Function(PreferredColorScheme previous, PreferredColorScheme current)
Callback invoked after an established preferred color scheme changes.
PreferredMotionCallback = void Function(PreferredMotion previous, PreferredMotion current)
Callback invoked after an established preferred-motion value changes.
Reducer<StateT, ActionT> = StateT Function(StateT state, ActionT action)
Combines a state and action into the next state.

Exceptions / Errors

ActionCancelledException
Thrown when a queued action is invalidated before it starts.
ActionDroppedException
Thrown when ActionConcurrency.drop rejects an overlapping dispatch.