Hooks¶
Hook primitives for @component functions: state, effects, memoization,
context, and refs. Hooks must be called at the top level of a component
(not inside conditionals or loops) so they can be matched to the same
slot across renders.
Hook primitives for function components.
Provides React-like hooks for managing state, effects, memoization, and
context within components decorated with
component. Hooks must be called at the top
level of a component (not inside conditionals or loops) so they map to
the same slot across renders. In dev mode the framework verifies this
and raises HookOrderError
on a violation instead of silently cross-wiring state.
Two effect phases exist, mirroring React:
use_layout_effectcallbacks run synchronously inside the commit, after native mutations and the layout pass have been applied. They can measure committed frames and issue imperative view commands before the user sees the new frame.use_effectcallbacks (passive effects) run after the layout effects, at the end of the same commit. An effect may be anasync def; it runs as a task on the framework loop and is cancelled when its dependencies change or the component unmounts.
The current hook state travels in a :mod:contextvars context rather
than a plain global, so async def component bodies keep their hook
identity across await boundaries even when several coroutine
renders interleave on the event loop.
Hooks talk to the reconciler through the small
RenderOwner protocol (mark a
component dirty, request a render, defer a transition, register a back
handler). That is the whole contract between the two modules.
Example
Classes:
| Name | Description |
|---|---|
RenderOwner |
What a hook needs from the object that renders its component. |
Ref |
Mutable container returned by |
HookState |
Per-instance storage for one component's hooks. |
QueryResult |
Snapshot of a |
MutationState |
Snapshot of a |
MutationCall |
Awaitable handle returned by a mutator trigger. |
Context |
A value shared with a subtree, created by |
Functions:
| Name | Description |
|---|---|
current_hook_state |
Return the active |
install_hook_state |
Install |
restore_hook_state |
Restore the hook state that was active before |
use_state |
Return |
use_reducer |
Return |
use_effect |
Schedule a side effect to run after the native commit. |
use_layout_effect |
Schedule a side effect that runs synchronously inside the commit. |
use_memo |
Return a memoized value that is recomputed only when |
use_callback |
Return a stable reference to |
use_ref |
Return a |
use_imperative_handle |
Publish a controller object on |
use_resource |
Start an async fetch and cache it across renders. |
use_transition |
Return |
use_deferred_value |
Return a copy of |
use_query |
Subscribe to an async fetcher and re-render when its result changes. |
use_mutation |
Wrap an async mutator with loading/error state and a trigger. |
use_subscription |
Subscribe to an external store and re-render when its snapshot changes. |
use_window_dimensions |
Return the current viewport size and re-render when it changes. |
use_safe_area_insets |
Return the current safe-area insets and re-render on change. |
use_keyboard_height |
Return the on-screen keyboard height (or 0) and re-render on change. |
use_color_scheme |
Return the effective color scheme and re-render when it changes. |
create_context |
Create a new context with an optional default value. |
use_context |
Read the current value of |
use_back_handler |
Intercept the system back action for this screen. |
RenderOwner
¶
Bases: Protocol
What a hook needs from the object that renders its component.
The reconciler implements this; tests may substitute a stub.
Methods:
| Name | Description |
|---|---|
mark_dirty |
Queue |
request_render |
Ask the host to flush dirty components (may be deferred). |
register_back_handler |
Register a system back-press handler; returns an unregister callable. |
Ref
¶
Ref(initial: Optional[T] = None)
Bases: Generic[T]
Mutable container returned by use_ref.
A Ref holds one value on its current attribute. Mutating
current never triggers a re-render, which makes refs the right
place for timers, last-seen values, and imperative handles.
When a Ref is passed to a built-in element via the ref=
prop, the reconciler populates current with the underlying
native view (UIView on iOS, android.view.View on Android,
a DOM element in the browser preview) after commit, and clears it back to
None on unmount. Composite components (e.g.
FlatList) instead publish a typed
controller object on current via
use_imperative_handle.
Attributes:
| Name | Type | Description |
|---|---|---|
current |
Optional[T]
|
The referenced value. |
HookState
¶
Per-instance storage for one component's hooks.
Each component instance owns one HookState. Hooks are matched
to slots by call order, so they must always be called in the same
order across renders. Effects scheduled during render are deferred
(layout effects into _pending_layout_effects, passive effects
into _pending_effects) and flushed by the reconciler in two
phases after native mutations commit.
Attributes:
| Name | Type | Description |
|---|---|---|
states |
List[Any]
|
One entry per |
effects |
List[Tuple[Any, Any]]
|
One |
layout_effects |
List[Tuple[Any, Any]]
|
One |
memos |
List[Tuple[Any, Any]]
|
One |
refs |
List[Ref]
|
One |
owner |
Optional[RenderOwner]
|
The |
vnode |
Any
|
The reconciler's node for this component, or |
Methods:
| Name | Description |
|---|---|
begin_render |
Prepare for a render pass: reset cursors and the dev-mode hook log. |
abort_render |
Roll back a suspended render's effect queue. |
finish_render |
Finalize a successful render: lock in / verify the hook signature. |
record_hook |
Record a hook call for the dev-mode order guard. |
reset_hook_signature |
Forget the recorded hook signature (used by Fast Refresh). |
flush_layout_effects |
Run layout effects queued during render (commit phase, pre-paint). |
flush_pending_effects |
Run passive effects queued during render, after native commit. |
cleanup_all_effects |
Run every outstanding cleanup function, then clear state. |
detach |
Break the back-references to the reconciler (on unmount). |
begin_render
¶
begin_render(component_name: str = '') -> None
Prepare for a render pass: reset cursors and the dev-mode hook log.
abort_render
¶
Roll back a suspended render's effect queue.
A suspended body re-runs from the top on retry, so any effects it queued before suspending would otherwise be queued twice.
finish_render
¶
Finalize a successful render: lock in / verify the hook signature.
Raises:
| Type | Description |
|---|---|
HookOrderError
|
In dev mode, when this render called fewer hooks than the previous one. |
record_hook
¶
record_hook(kind: str) -> None
Record a hook call for the dev-mode order guard.
Raises:
| Type | Description |
|---|---|
HookOrderError
|
In dev mode, when the hook at this position differs from (or extends past) the previous render. |
reset_hook_signature
¶
Forget the recorded hook signature (used by Fast Refresh).
flush_layout_effects
¶
Run layout effects queued during render (commit phase, pre-paint).
flush_pending_effects
¶
Run passive effects queued during render, after native commit.
For each pending effect, the previous cleanup is invoked first
(if any), then the new effect callback. The new return value
becomes the next cleanup. Effects that are async def (or
that return an awaitable) run as tasks on the framework loop;
their cleanup cancels the task, and a callable returned by the
coroutine runs as an additional cleanup once it completed.
cleanup_all_effects
¶
Run every outstanding cleanup function, then clear state.
Layout-effect cleanups run before passive-effect cleanups,
matching the mount order in reverse. Also cancels in-flight
resources and any pending async def body. Called when the
component instance is unmounted by the reconciler.
detach
¶
Break the back-references to the reconciler (on unmount).
Lets the unmounted component's hook state (and the closures it captured) be freed by plain refcounting, which matters on iOS where the cyclic GC is disabled.
QueryResult
dataclass
¶
QueryResult(
data: Optional[T] = None,
loading: bool = True,
error: Optional[BaseException] = None,
refetch: Callable[[], None] = lambda: None,
)
Bases: Generic[T]
Snapshot of a use_query subscription.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
Optional[T]
|
The most recent successful result, or the |
loading |
bool
|
|
error |
Optional[BaseException]
|
The exception raised by the most recent failed fetch,
or |
refetch |
Callable[[], None]
|
A zero-arg callable that triggers a refetch. Stable across renders. |
MutationState
dataclass
¶
MutationState(
data: Optional[T] = None,
loading: bool = False,
error: Optional[BaseException] = None,
)
Bases: Generic[T]
Snapshot of a use_mutation subscription.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
Optional[T]
|
The most recent successful return value of the mutator,
or |
loading |
bool
|
|
error |
Optional[BaseException]
|
The exception raised by the most recent failed
mutation, or |
MutationCall
¶
MutationCall(future: Any)
Bases: Generic[T]
Awaitable handle returned by a mutator trigger.
Returned by the second element of the
use_mutation tuple. Awaiting the
handle resolves to the mutator's return value (or re-raises its
exception); discarding the handle is safe. Python won't warn
about an unawaited coroutine because this is a plain object.
Example
Methods:
| Name | Description |
|---|---|
cancel |
Cancel the underlying mutation. Returns whether cancellation succeeded. |
done |
Whether the underlying mutation has finished. |
Context
¶
Bases: Generic[T]
A value shared with a subtree, created by create_context.
Provide a value with Provider
and read it with use_context. A
Context is itself an element type: ctx.Provider(value, ...)
returns an element whose type is ctx.
Context is reactive: when a Provider's value changes, every component that read the context on its last render re-renders, even if a memoized ancestor skipped its own re-render.
Attributes:
| Name | Type | Description |
|---|---|---|
default |
The value returned when no Provider ancestor exists. |
|
name |
Optional label for diagnostics. |
Methods:
| Name | Description |
|---|---|
Provider |
Provide |
current |
Return the innermost provided value, or |
Provider
¶
Provide value to every descendant of children.
A Provider contributes no native view of its own; its children mount directly into the surrounding native parent.
When value differs from the previous render (identity, then
==), every descendant that read the context re-renders,
including descendants of memoized components that skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
Value made available to descendants. |
required |
*children
|
Node
|
Subtree(s) under which the provider applies. |
()
|
key
|
Optional[str]
|
Stable identity for keyed reconciliation. |
None
|
provider_environment
¶
Return the current immutable provider environment for render identity.
current_hook_state
¶
Return the active HookState, or None if no render is in flight.
install_hook_state
¶
Install state as the active HookState; returns the reset token.
restore_hook_state
¶
Restore the hook state that was active before install_hook_state.
use_state
¶
use_state() -> Tuple[Optional[Any], StateSetter[Any]]
use_state(
initial: Callable[[], T],
) -> Tuple[T, StateSetter[T]]
use_state(initial: T) -> Tuple[T, StateSetter[T]]
use_state(
initial: Any = None,
) -> Tuple[Any, StateSetter[Any]]
Return (value, setter) for component-local state.
State persists across re-renders of the same component instance.
The setter accepts a value or a current -> new callable; calling
it with an unchanged value is a no-op (no re-render).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial
|
Any
|
Initial state value. If callable, it is invoked once on the first render (lazy initialization). |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A 2-tuple |
StateSetter[Any]
|
state and |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_reducer
¶
use_reducer(
reducer: Callable[[T, Any], T],
initial_state: Union[T, Callable[[], T]],
) -> Tuple[T, Callable[[Any], None]]
Return (state, dispatch) for reducer-based state management.
A reducer is a pure function that takes the current state and an
action and returns the next state. Use it instead of
use_state when state transitions are
complex enough that centralizing them in one function aids
readability and testing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reducer
|
Callable[[T, Any], T]
|
|
required |
initial_state
|
Union[T, Callable[[], T]]
|
Initial state value, or a callable invoked once on the first render. |
required |
Returns:
| Type | Description |
|---|---|
T
|
A 2-tuple |
Callable[[Any], None]
|
reducer with the supplied action. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_effect
¶
Schedule a side effect to run after the native commit.
Effects are queued during the render pass and flushed once the reconciler has finished applying all native-view mutations, which means effect callbacks can safely measure layout or interact with committed native views.
The deps argument controls when the effect re-runs:
None: every render.[]: mount only.[a, b]: whenaorbchange (compared by identity, then==).
A synchronous effect may return a cleanup callable; the previous
cleanup runs before the next effect (and on unmount).
An async effect (an async def) runs as a task on the
framework loop. When deps change or the component unmounts, the
in-flight task is cancelled (:class:asyncio.CancelledError is
raised at its current await), giving async effects structured
cancellation for free. If the coroutine finishes and returns a
callable, that callable runs as the cleanup instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
effect
|
Callable[[], Any]
|
A zero-arg callable invoked after commit: either a
synchronous function (optionally returning a cleanup
callable) or an |
required |
deps
|
Optional[list]
|
Dependency list, or |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_layout_effect
¶
Schedule a side effect that runs synchronously inside the commit.
Like use_effect, but the callback
fires before passive effects, immediately after native mutations
and the layout pass are applied. Use it when you need to measure a
committed frame (via a Ref) or issue an
imperative view command before the user sees the new frame, for
example scrolling a list into position on mount.
Prefer use_effect for everything else; layout effects block the
commit, so heavy work here delays the frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
effect
|
Callable[[], Any]
|
A zero-arg callable invoked during commit. Optionally returns a cleanup callable. |
required |
deps
|
Optional[list]
|
Dependency list, or |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_memo
¶
Return a memoized value that is recomputed only when deps change.
Use this for expensive computations whose inputs change rarely. For cheap computations, plain inline code is faster (memoization itself has overhead).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factory
|
Callable[[], T]
|
Zero-arg callable returning the value. |
required |
deps
|
list
|
Dependency list. The value is recomputed when any element differs from the previous render. |
required |
Returns:
| Type | Description |
|---|---|
T
|
The cached or freshly computed value. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_callback
¶
use_callback(callback: F, deps: list) -> F
Return a stable reference to callback, refreshed when deps change.
Equivalent to use_memo(lambda: callback, deps). Useful when
passing a function as a prop to a memoized child component, so the
child doesn't see a fresh function identity on every render.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
F
|
The callable to memoize. |
required |
deps
|
list
|
Dependency list controlling when the reference refreshes. |
required |
Returns:
| Type | Description |
|---|---|
F
|
A callable with stable identity across renders (until |
use_ref
¶
Return a Ref that persists across renders.
Refs are useful for storing values that must survive renders without triggering them: timers, last-seen values, native handles, and so on.
ref.current is also populated by the reconciler with the
underlying native view when the ref is passed via the ref= prop
on a built-in element, and cleared to None when that element
unmounts. Composite components such as
FlatList publish a typed controller
object instead (see
use_imperative_handle).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial
|
Optional[T]
|
Value placed at |
None
|
Returns:
| Type | Description |
|---|---|
Ref[T]
|
A |
Ref[T]
|
not trigger re-renders. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_imperative_handle
¶
use_imperative_handle(
ref: Optional[Ref[Any]],
factory: Callable[[], Any],
deps: Optional[list] = None,
) -> None
Publish a controller object on ref.current.
The composite-component counterpart to passing ref= to a
built-in element. Call it inside a component that accepts a
ref prop to expose a curated imperative API (rather than the
raw native view) to the parent. The handle is installed during the
commit's layout-effect phase and cleared back to None on
unmount.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
Optional[Ref[Any]]
|
The |
required |
factory
|
Callable[[], Any]
|
Zero-arg callable returning the handle object. |
required |
deps
|
Optional[list]
|
Dependency list controlling when the handle is rebuilt.
|
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_resource
¶
Start an async fetch and cache it across renders.
The fetch starts immediately (during render, not after commit) and
the resulting Resource is cached until
deps change, at which point the old fetch is cancelled and a
new one starts. Because results are cached, re-renders resolve
instantly; only genuinely new data suspends.
Consume the resource with resource.read() (suspends the render
while pending; pair with a Suspense
boundary) or await resource inside an async def component.
Errors raised by the fetcher re-raise at the read site, so an
enclosing ErrorBoundary catches
failures declaratively.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fetcher
|
Callable[[], Any]
|
Zero-arg |
required |
deps
|
Optional[list]
|
Dependency list controlling when to refetch. Defaults to
|
None
|
Returns:
| Type | Description |
|---|---|
Resource[Any]
|
The cached |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_transition
¶
Return (is_pending, start_transition) for low-priority updates.
State updates made inside start_transition(fn) are marked as
transitions: instead of re-rendering synchronously, their render
is deferred to a later turn of the framework loop, so urgent
updates (typing, presses) queued in the meantime render first.
is_pending is True from the moment start_transition is
called until the deferred render has committed, which is exactly
when to show a lightweight busy indicator.
Returns:
| Type | Description |
|---|---|
Tuple[bool, Callable[[Callable[[], None]], None]]
|
A 2-tuple |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
Example
@pn.component
def Search():
query, set_query = pn.use_state("")
results_for, set_results_for = pn.use_state("")
is_pending, start_transition = pn.use_transition()
def on_change(text):
set_query(text) # urgent: keep the input responsive
start_transition(lambda: set_results_for(text))
return pn.Column(
pn.TextInput(value=query, on_change=on_change),
pn.ActivityIndicator() if is_pending else Results(results_for),
)
use_deferred_value
¶
Return a copy of value that lags behind during fast updates.
The returned value updates in a deferred (transition-priority)
render after the urgent render that changed value has
committed. Pass the deferred value to expensive subtrees (a
filtered list, a chart) so the urgent part of the UI stays
responsive while the expensive part catches up a beat later.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The latest value. |
required |
Returns:
| Type | Description |
|---|---|
T
|
The previous value while a newer one is still being adopted, |
T
|
then the latest value. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_query
¶
use_query(
fetcher: Callable[[], Awaitable[T]],
deps: Optional[list] = None,
*,
initial: Optional[T] = None,
key: Any = None,
client: Any = None
) -> QueryResult[T]
Subscribe to an async fetcher and re-render when its result changes.
The fetcher is called on mount and any time deps change, with
cancellation propagated when the component unmounts mid-fetch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fetcher
|
Callable[[], Awaitable[T]]
|
Zero-arg |
required |
deps
|
Optional[list]
|
Dependency list. Refetches whenever any entry changes. |
None
|
initial
|
Optional[T]
|
Optional starting value for |
None
|
key
|
Any
|
Explicit hashable key for sharing results across subscribers.
Include every input that identifies the shared result. Without a
key, the query belongs to this hook and changes with |
None
|
client
|
Any
|
QueryClient owning the shared cache. Defaults to the application's client. |
None
|
Returns:
| Type | Description |
|---|---|
QueryResult[T]
|
A frozen |
QueryResult[T]
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_mutation
¶
use_mutation(
mutator: Callable[..., Awaitable[T]],
) -> Tuple[
MutationState[T], Callable[..., MutationCall[T]]
]
Wrap an async mutator with loading/error state and a trigger.
Returns (state, mutate). Call mutate(*args, **kwargs) to
invoke the mutator; state reflects loading/error/data and
re-renders on each transition. mutate returns a
MutationCall you can await for
the result, or discard for fire-and-forget.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mutator
|
Callable[..., Awaitable[T]]
|
An |
required |
Returns:
| Type | Description |
|---|---|
Tuple[MutationState[T], Callable[..., MutationCall[T]]]
|
A 2-tuple |
use_subscription
¶
use_subscription(
subscribe: Callable[
[Callable[[], None]], Callable[[], None]
],
get_snapshot: Callable[[], T],
) -> T
Subscribe to an external store and re-render when its snapshot changes.
The Pythonic counterpart of React's useSyncExternalStore: the
platform-metric hooks below are built on it, and it's the right
primitive for app-level stores that live outside the component
tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subscribe
|
Callable[[Callable[[], None]], Callable[[], None]]
|
|
required |
get_snapshot
|
Callable[[], T]
|
Zero-arg callable returning the current value. Re-read on every render. |
required |
Returns:
| Type | Description |
|---|---|
T
|
The current snapshot. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_window_dimensions
¶
use_window_dimensions() -> WindowDimensions
Return the current viewport size and re-render when it changes.
Equivalent to React Native's useWindowDimensions. The values
are pushed by the screen host whenever the platform reports a new
size (initial layout, rotation, multitasking split-view).
Returns:
| Type | Description |
|---|---|
WindowDimensions
|
|
WindowDimensions
|
named tuple with |
WindowDimensions
|
units (pt on iOS, dp on Android). Both are |
WindowDimensions
|
screen host has run its first layout pass. Being a tuple, it |
WindowDimensions
|
unpacks ( |
WindowDimensions
|
compares by value. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_safe_area_insets
¶
use_safe_area_insets() -> SafeAreaInsets
Return the current safe-area insets and re-render on change.
Mirrors react-native-safe-area-context's useSafeAreaInsets.
Returns:
| Type | Description |
|---|---|
SafeAreaInsets
|
|
SafeAreaInsets
|
named tuple with |
SafeAreaInsets
|
floats in layout units (pt on iOS, dp on Android). |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_keyboard_height
¶
use_keyboard_height() -> float
Return the on-screen keyboard height (or 0) and re-render on change.
Useful for custom layout that needs to react to keyboard
show/hide events. Most apps should use
KeyboardAvoidingView instead
of reading this directly.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_color_scheme
¶
use_color_scheme() -> str
Return the effective color scheme and re-render when it changes.
Equivalent to React Native's useColorScheme. The system value
is published by the screen host; an app-level override set through
appearance.set_color_scheme
takes precedence.
Returns:
| Type | Description |
|---|---|
str
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
create_context
¶
Create a new context with an optional default value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
T
|
Returned by |
None
|
name
|
Optional[str]
|
Optional label shown in diagnostics. |
None
|
Returns:
| Type | Description |
|---|---|
Context[T]
|
A fresh |
use_context
¶
use_context(context: Context[T]) -> T
Read the current value of context from the nearest Provider.
If no enclosing Provider exists, returns the context's default. The component is registered as a subscriber: when the nearest Provider's value changes, the component re-renders even if a memoized ancestor skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Context[T]
|
The |
required |
Returns:
| Type | Description |
|---|---|
T
|
The current value for |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
use_back_handler
¶
Intercept the system back action for this screen.
On Android this handles the hardware back button and predictive back gesture; in the browser preview it handles the Escape key. iOS has no system back button, so the handler never fires there (swipe-back is controlled by the navigation stack instead).
Handlers registered later run first, so a component mounted on top
of existing content (a modal, a confirmation sheet) takes priority
over handlers that were already mounted. Return True to consume
the event and stop both remaining handlers and the platform's
default behavior (popping the screen); return False to pass it
along.
The latest handler closure from the most recent render is
always the one invoked; registration order is fixed at mount, so
re-renders never change priority.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
Callable[[], bool]
|
Zero-arg callable returning |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside a |
Async hooks¶
For coroutines and data-driven UI, PythonNative ships dedicated
async-aware hooks layered on top of use_state / use_effect:
use_effectacceptsasync defcallbacks directly; the coroutine runs as a task and is cancelled on re-run / unmount.use_resource: starts a fetch during render and caches it; reading a pendingResourcesuspends the render (pair withSuspense).use_transition/use_deferred_value: mark expensive updates as low priority so urgent updates render first.use_query: subscribes to an async fetcher and re-renders on data / error / refetch.use_mutation: wraps an async mutator with loading / error state and a trigger.use_persisted_state:use_statebacked byAsyncStorage.
See the Async + data guide for a complete walkthrough.
Platform-metric hooks¶
These hooks subscribe to values published by
pythonnative.platform_metrics and re-render the component when they
change. The screen host is the only code that updates the underlying
values; user code consumes them.
use_window_dimensions: viewport size.use_safe_area_insets: top/bottom/left/right insets.use_keyboard_height: software keyboard height.
For most apps the dedicated
KeyboardAvoidingView component
is preferable to consuming use_keyboard_height directly.
Batching and transitions¶
State setters schedule a render through pythonnative.scheduler.
batch_updates coalesces
several setter calls into one render, and each reconciler owns a
TransitionQueue that
defers renders started inside
use_transition.
Update scheduling primitives shared by hooks and the reconciler.
Two pieces live here:
batch_updates, a context manager that coalesces the render triggers fired by several state setters into one, tracked per execution context (so it composes withasynccode).TransitionQueue, the per-reconciler queue behinduse_transition: renders marked as transitions are deferred to a later turn of the framework loop so urgent updates (typing, presses) stay responsive.
Nothing here is global mutable state beyond context variables, so several reconcilers (screens, list rows, tests) never interfere.
Classes:
| Name | Description |
|---|---|
TransitionQueue |
Deferred render triggers and completion callbacks for one reconciler. |
Functions:
| Name | Description |
|---|---|
schedule_trigger |
Run |
batch_updates |
Coalesce multiple state updates into a single re-render. |
in_transition |
Whether state updates in the current context are transitions. |
run_in_transition |
Run |
TransitionQueue
¶
Deferred render triggers and completion callbacks for one reconciler.
Triggers added via defer
run together on a later loop turn; callbacks added via
on_complete
run right after them (this is how use_transition flips its
is_pending flag back off once the deferred render committed).
Methods:
| Name | Description |
|---|---|
defer |
Queue |
on_complete |
Queue |
flush |
Run every deferred trigger, then the completion callbacks. |
clear |
Drop queued work (used on unmount). |
Attributes:
| Name | Type | Description |
|---|---|---|
pending |
bool
|
Whether a flush is scheduled or work is queued. |
schedule_trigger
¶
schedule_trigger(trigger: Callable[[], None]) -> None
Run trigger now, or defer it to the end of the enclosing batch_updates block.
batch_updates
¶
batch_updates() -> Generator[None, None, None]
Coalesce multiple state updates into a single re-render.
State setters called inside the with block defer their
re-render trigger until the block exits, so any number of
set_* calls produce at most one render pass.
Next steps¶
- Compose hooks into a screen: Components.
- Run side effects from
use_effect(after commit) anduse_focus_effect(after focus). - Share state across the tree with
create_contextandContext.Provider. - Animate without re-rendering using
use_ref Animated; see the Animations guide.