Skip to content

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_effect callbacks 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_effect callbacks (passive effects) run after the layout effects, at the end of the same commit. An effect may be an async 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
import pythonnative as pn

@pn.component
def Counter(initial: int = 0):
    count, set_count = pn.use_state(initial)
    return pn.Column(
        pn.Text(f"Count: {count}"),
        pn.Button("+", on_press=lambda: set_count(count + 1)),
    )

Classes:

Name Description
RenderOwner

What a hook needs from the object that renders its component.

Ref

Mutable container returned by use_ref.

HookState

Per-instance storage for one component's hooks.

QueryResult

Snapshot of a use_query subscription.

MutationState

Snapshot of a use_mutation subscription.

MutationCall

Awaitable handle returned by a mutator trigger.

Context

A value shared with a subtree, created by create_context.

Functions:

Name Description
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

Return (value, setter) for component-local state.

use_reducer

Return (state, dispatch) for reducer-based state management.

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 deps change.

use_callback

Return a stable reference to callback, refreshed when deps change.

use_ref

Return a Ref that persists across renders.

use_imperative_handle

Publish a controller object on ref.current.

use_resource

Start an async fetch and cache it across renders.

use_transition

Return (is_pending, start_transition) for low-priority updates.

use_deferred_value

Return a copy of value that lags behind during fast updates.

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 context from the nearest Provider.

use_back_handler

Intercept the system back action for this screen.

StateSetter module-attribute

StateSetter = Callable[
    [Union[T, Callable[[T], T]]], None
]

Setter returned by use_state: accepts a value or current -> new.

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 vnode's component for a local re-render.

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.

mark_dirty

mark_dirty(vnode: Any) -> None

Queue vnode's component for a local re-render.

request_render

request_render() -> None

Ask the host to flush dirty components (may be deferred).

register_back_handler

register_back_handler(
    handler: Callable[[], bool],
) -> Callable[[], None]

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. None until populated.

HookState

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 use_state / use_reducer call.

effects List[Tuple[Any, Any]]

One (deps, cleanup) tuple per use_effect call.

layout_effects List[Tuple[Any, Any]]

One (deps, cleanup) tuple per use_layout_effect call.

memos List[Tuple[Any, Any]]

One (deps, value) tuple per use_memo / use_callback.

refs List[Ref]

One Ref per use_ref call.

owner Optional[RenderOwner]

The RenderOwner (reconciler) this component is mounted in, or None.

vnode Any

The reconciler's node for this component, or None.

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

abort_render() -> None

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

finish_render() -> None

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

reset_hook_signature() -> None

Forget the recorded hook signature (used by Fast Refresh).

flush_layout_effects

flush_layout_effects() -> None

Run layout effects queued during render (commit phase, pre-paint).

flush_pending_effects

flush_pending_effects() -> None

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

cleanup_all_effects() -> None

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

detach() -> None

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 initial value before the first fetch completes.

loading bool

True while a fetch is in flight (including the initial fetch and any refetches).

error Optional[BaseException]

The exception raised by the most recent failed fetch, or None if no fetch has failed since the last success.

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 None if no mutation has succeeded yet.

loading bool

True while a mutation is in flight.

error Optional[BaseException]

The exception raised by the most recent failed mutation, or None.

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
# Fire-and-forget:
save_button.on_press = lambda: mutate(post)

# Or await for the result:
async def submit():
    try:
        created = await mutate(post)
    except ApiError as exc:
        await pn.Alert.show(title="Save failed", message=str(exc))

Methods:

Name Description
cancel

Cancel the underlying mutation. Returns whether cancellation succeeded.

done

Whether the underlying mutation has finished.

cancel

cancel() -> bool

Cancel the underlying mutation. Returns whether cancellation succeeded.

done

done() -> bool

Whether the underlying mutation has finished.

Context

Context(default: T, name: Optional[str] = None)

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 value to every descendant of children.

current

Return the innermost provided value, or default.

Provider

Provider(
    value: T, *children: Node, key: Optional[str] = None
) -> Element

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
Example
Theme = pn.create_context({"primary": "#007AFF"})

@pn.component
def App():
    return Theme.Provider({"primary": "#FF0000"}, Header(), Body())

current

current() -> T

Return the innermost provided value, or default.

provider_environment

provider_environment() -> Dict[int, Any]

Return the current immutable provider environment for render identity.

current_hook_state

current_hook_state() -> Optional[HookState]

Return the active HookState, or None if no render is in flight.

install_hook_state

install_hook_state(
    state: Optional[HookState],
) -> Token[Optional[HookState]]

Install state as the active HookState; returns the reset token.

restore_hook_state

restore_hook_state(
    token: Token[Optional[HookState]],
) -> None

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 (value, setter) where value is the current

StateSetter[Any]

state and setter updates it (and triggers a re-render).

Raises:

Type Description
RuntimeError

If called outside a @component function.

Example
import pythonnative as pn

@pn.component
def Counter():
    count, set_count = pn.use_state(0)
    return pn.Button(
        f"Count: {count}",
        on_press=lambda: set_count(count + 1),
    )

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]

reducer(current_state, action) -> new_state. The component re-renders only when reducer returns a value different from the current state.

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 (state, dispatch) where dispatch runs the

Callable[[Any], None]

reducer with the supplied action.

Raises:

Type Description
RuntimeError

If called outside a @component function.

use_effect

use_effect(
    effect: Callable[[], Any], deps: Optional[list] = None
) -> None

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]: when a or b change (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 async def.

required
deps Optional[list]

Dependency list, or None to run on every render.

None

Raises:

Type Description
RuntimeError

If called outside a @component function.

Example
import asyncio
import time

import pythonnative as pn

@pn.component
def Clock():
    now, set_now = pn.use_state("")

    async def tick():
        while True:
            set_now(time.strftime("%H:%M:%S"))
            await asyncio.sleep(1)

    pn.use_effect(tick, [])
    return pn.Text(now)

use_layout_effect

use_layout_effect(
    effect: Callable[[], Any], deps: Optional[list] = None
) -> None

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 to run on every render.

None

Raises:

Type Description
RuntimeError

If called outside a @component function.

use_memo

use_memo(factory: Callable[[], T], deps: list) -> T

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 @component function.

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

use_ref

use_ref(initial: Optional[T] = None) -> Ref[T]

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 ref.current on first render.

None

Returns:

Type Description
Ref[T]

A Ref. Mutations to ref.current do

Ref[T]

not trigger re-renders.

Raises:

Type Description
RuntimeError

If called outside a @component function.

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 Ref received via the component's ref prop. None is allowed (the parent didn't request a handle), in which case this is a no-op.

required
factory Callable[[], Any]

Zero-arg callable returning the handle object.

required
deps Optional[list]

Dependency list controlling when the handle is rebuilt. None rebuilds on every render, matching effects.

None

Raises:

Type Description
RuntimeError

If called outside a @component function.

Example
@pn.component
def VideoPlayer(source: str, ref: pn.Ref | None = None):
    pn.use_imperative_handle(ref, lambda: PlayerController(...), [source])
    return pn.View(...)

use_resource

use_resource(
    fetcher: Callable[[], Any], deps: Optional[list] = None
) -> Resource[Any]

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 async def (or plain callable) producing the value. Synchronous fetchers resolve immediately and never suspend.

required
deps Optional[list]

Dependency list controlling when to refetch. Defaults to [] (fetch once per component instance).

None

Returns:

Type Description
Resource[Any]

The cached Resource.

Raises:

Type Description
RuntimeError

If called outside a @component function.

Example
@pn.component
async def UserCard(user_id: str):
    user = await pn.use_resource(lambda: api.get_user(user_id), [user_id])
    return pn.Text(user["name"])

use_transition

use_transition() -> (
    Tuple[bool, Callable[[Callable[[], None]], None]]
)

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 (is_pending, start_transition).

Raises:

Type Description
RuntimeError

If called outside a @component function.

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

use_deferred_value(value: T) -> T

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 @component function.

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 async callable that resolves to the current data.

required
deps Optional[list]

Dependency list. Refetches whenever any entry changes.

None
initial Optional[T]

Optional starting value for data before the first fetch completes.

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

None
client Any

QueryClient owning the shared cache. Defaults to the application's client.

None

Returns:

Type Description
QueryResult[T]

A frozen QueryResult with

QueryResult[T]

data / loading / error / refetch.

Raises:

Type Description
RuntimeError

If called outside a @component function.

Example
@pn.component
def UserCard(user_id: str):
    q = pn.use_query(lambda: api.get_user(user_id), [user_id])
    if q.loading:
        return pn.Text("Loading...")
    if q.error:
        return pn.Text(f"Error: {q.error}")
    return pn.Text(q.data["name"])

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 async callable that performs the side effect and returns the resulting data.

required

Returns:

Type Description
Tuple[MutationState[T], Callable[..., MutationCall[T]]]

A 2-tuple (state, mutate).

Example
@pn.component
def NewPostForm():
    state, save = pn.use_mutation(api.create_post)

    return pn.Column(
        pn.Button("Save", on_press=lambda: save(post)),
        state.loading and pn.Text("Saving..."),
        state.error and pn.Text(str(state.error)),
    )

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]]

subscribe(on_change) -> unsubscribe. Called once on mount; on_change must be invoked whenever the store changes.

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 @component function.

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 width and height floats in layout

WindowDimensions

units (pt on iOS, dp on Android). Both are 0.0 until the

WindowDimensions

screen host has run its first layout pass. Being a tuple, it

WindowDimensions

unpacks (width, height = pn.use_window_dimensions()) and

WindowDimensions

compares by value.

Raises:

Type Description
RuntimeError

If called outside a @component function.

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 top, left, bottom, and right

SafeAreaInsets

floats in layout units (pt on iOS, dp on Android).

Raises:

Type Description
RuntimeError

If called outside a @component function.

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 @component function.

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

"light" or "dark".

Raises:

Type Description
RuntimeError

If called outside a @component function.

create_context

create_context(
    default: T = None, *, name: Optional[str] = None
) -> Context[T]

Create a new context with an optional default value.

Parameters:

Name Type Description Default
default T

Returned by use_context when there is no enclosing Provider.

None
name Optional[str]

Optional label shown in diagnostics.

None

Returns:

Type Description
Context[T]

A fresh Context.

Example
Theme = pn.create_context({"primary": "#007AFF"}, name="Theme")

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 Context to read from.

required

Returns:

Type Description
T

The current value for context.

Raises:

Type Description
RuntimeError

If called outside a @component function.

use_back_handler

use_back_handler(handler: Callable[[], bool]) -> None

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 True if it consumed the back action.

required

Raises:

Type Description
RuntimeError

If called outside a @component function.

Example
@pn.component
def Editor():
    dirty, set_dirty = pn.use_state(False)
    pn.use_back_handler(lambda: dirty)  # block back while dirty
    ...

Async hooks

For coroutines and data-driven UI, PythonNative ships dedicated async-aware hooks layered on top of use_state / use_effect:

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.

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 with async code).
  • TransitionQueue, the per-reconciler queue behind use_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 trigger now, or defer it to the end of the enclosing batch_updates block.

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 fn with its state updates marked as transitions.

TransitionQueue

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 trigger for the next flush.

on_complete

Queue callback to run after the next flush's triggers.

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.

pending property

pending: bool

Whether a flush is scheduled or work is queued.

defer

defer(trigger: Callable[[], None]) -> None

Queue trigger for the next flush.

on_complete

on_complete(callback: Callable[[], None]) -> None

Queue callback to run after the next flush's triggers.

flush

flush() -> None

Run every deferred trigger, then the completion callbacks.

clear

clear() -> None

Drop queued work (used on unmount).

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.

Example
import pythonnative as pn

with pn.batch_updates():
    set_count(1)
    set_name("hello")

in_transition

in_transition() -> bool

Whether state updates in the current context are transitions.

run_in_transition

run_in_transition(fn: Callable[[], None]) -> None

Run fn with its state updates marked as transitions.

Next steps