Skip to content

Context and refs

Context shares a value with a subtree without manually passing it through every component:

from pyreact_forge import component, create_context, html, use_context

Theme = create_context("light")

@component
def Status():
    theme = use_context(Theme)
    return html.p(f"Theme: {theme}")

@component
def App():
    return Theme.provide(Status(), value="dark")

Creating context is a runtime operation: the module is loaded inside the browser or SSR environment. Importing and executing this whole app module in ordinary CPython is not a way to render it.

DOM refs

from pyreact_forge import component, html, use_ref

@component
def App():
    field = use_ref()
    return html.div(
        html.input(ref=field, aria_label="Search"),
        html.button("Focus search", on_click=lambda: field.current.focus()),
    )

field.current is assigned when React commits the element. It is not available while creating the initial render. Updating a ref does not itself cause a render.

For custom components, @forward_ref receives (props, ref). The use_imperative_handle hook exposes a deliberate custom handle. Class component refs currently expose the JS adapter; they are not a transparent Python instance reference. See the API guide for that boundary.