Skip to main content

Hooks

Struct Hooks 

Source
pub struct Hooks<P: 'static, S: 'static> { /* private fields */ }
Expand description

Effect collector for declarative lifecycle management.

Components receive a Hooks instance in their #[component] function body and use it to declare effects. The framework runs the component function after every build and update, clearing old effects and applying the new set — so effects are always consistent with current props and state.

The type parameter P is the component’s props type, and S is the component’s state type. Hook callbacks receive &P (props) adjacent to &mut S or &mut Tracked<S> (state), giving them access to the component’s current props without cloning.

§Available hooks

HookFires when
use_intervalPeriodically, at the given duration
use_mountOnce, after the component is first built
use_unmountOnce, when the component is removed
use_autofocusRequests focus when the component mounts
use_focus_scopeCreates a focus scope boundary for Tab cycling
provide_contextMakes a value available to descendants
use_contextReads a value provided by an ancestor

§Example

#[component(props = Timer, state = TimerState)]
fn timer(props: &Timer, state: &TimerState, hooks: &mut Hooks<Timer, TimerState>) -> Elements {
    if props.running {
        hooks.use_interval(Duration::from_secs(1), |_props, s| s.elapsed += 1);
    }
    hooks.use_mount(|_props, s| s.started_at = Instant::now());
    hooks.use_unmount(|_props, s| println!("ran for {:?}", s.started_at.elapsed()));
    // ... return element tree
}

Implementations§

Source§

impl<P: Send + Sync + 'static, S: Send + Sync + 'static> Hooks<P, S>

Source

pub fn new() -> Self

Create a new empty hooks instance.

Source

pub fn use_interval( &mut self, interval: Duration, handler: impl Fn(&P, &mut Tracked<S>) + Send + Sync + 'static, )

Register a periodic interval effect.

The handler is called each time interval elapses during the framework’s tick cycle. The handler receives the component’s current props and &mut Tracked<State>. Mutations through DerefMut automatically mark the component dirty; use Tracked::read() to access state without triggering a re-render.

Commonly used for animations (e.g., the built-in Spinner uses an 80ms interval to cycle frames).

Source

pub fn use_mount( &mut self, handler: impl Fn(&P, &mut Tracked<S>) + Send + Sync + 'static, )

Register a mount effect that fires once after the component is built.

Use this for one-time initialization that depends on state being available (e.g., recording a start time, fetching initial data).

Source

pub fn use_unmount( &mut self, handler: impl Fn(&P, &mut Tracked<S>) + Send + Sync + 'static, )

Register an unmount effect that fires when the component is removed from the tree.

Use this for cleanup: logging, cancelling external resources, etc.

Source

pub fn use_autofocus(&mut self)

Request focus when this node mounts.

If multiple nodes mount with autofocus in the same rebuild, the last one wins.

Source

pub fn use_focus_scope(&mut self)

Mark this node as a focus scope boundary.

Tab/Shift-Tab cycling is confined to focusable descendants within this scope. Scopes nest — the deepest enclosing scope wins. When this node is removed from the tree, focus is restored to whatever was focused before the scope captured it.

Source

pub fn provide_context<T: Any + Send + Sync>(&mut self, value: T)

Provide a context value to all descendant components.

The value is available during this reconciliation pass to any descendant that calls use_context with the same type T. If an ancestor already provides T, this component’s value shadows it for the subtree.

§Example
#[component(props = MyProvider, children = Elements)]
fn my_provider(props: &MyProvider, hooks: &mut Hooks<MyProvider, ()>, children: Elements) -> Elements {
    hooks.provide_context(props.event_sender.clone());
    children
}
Source

pub fn use_context<T: Any + Send + Sync + 'static>( &mut self, handler: impl FnOnce(Option<&T>, &P, &mut Tracked<S>) + Send + 'static, )

Read a context value provided by an ancestor component.

The handler is called with Option<&T> (the context value, or None if no ancestor provides T), &P (the component’s current props), and &mut Tracked<S> (the component’s mutable state). The handler always fires — use the Option to handle the absent case.

The handler runs during reconciliation, after the component function returns.

§Example
#[component(props = MyButton, state = MyState)]
fn my_button(props: &MyButton, hooks: &mut Hooks<MyButton, MyState>) -> Elements {
    hooks.use_context::<Sender<AppEvent>>(|sender, _props, state| {
        state.tx = sender.cloned();
    });
    // ... return element tree
}
Source

pub fn use_focusable(&mut self, focusable: bool)

Declare this component as focusable (or not).

Focusable components participate in Tab cycling. This overrides the component’s is_focusable trait method.

Source

pub fn use_cursor( &mut self, handler: impl Fn(Rect, &P, &S) -> Option<(u16, u16)> + Send + Sync + 'static, )

Declare a cursor position callback for when this component has focus.

Returns (col, row) relative to the component’s render area, or None to hide the cursor. This overrides the component’s cursor_position trait method.

Source

pub fn use_event( &mut self, handler: impl Fn(&Event, &P, &mut Tracked<S>) -> EventResult + Send + Sync + 'static, )

Declare an event handler for the bubble phase (focused → root).

Return EventResult::Consumed to stop propagation. This overrides the component’s handle_event trait method.

The handler receives the event, the component’s current props, and &mut Tracked<S> — only mutations through DerefMut mark the component dirty, matching the trait API behavior.

Source

pub fn use_event_capture( &mut self, handler: impl Fn(&Event, &P, &mut Tracked<S>) -> EventResult + Send + Sync + 'static, )

Declare an event handler for the capture phase (root → focused).

The capture phase fires before the bubble phase. Return EventResult::Consumed to prevent the event from reaching the focused component.

Source

pub fn use_layout(&mut self, layout: Layout)

Declare this component’s layout direction.

Override the component’s layout trait method. Use Layout::Horizontal for side-by-side children.

Source

pub fn use_width_constraint(&mut self, constraint: WidthConstraint)

Declare this component’s width constraint within a horizontal parent.

Override the component’s width_constraint trait method.

Source

pub fn use_height_hint(&mut self, height: u16)

Declare a fixed height for this component.

The framework skips probe-render measurement and uses this value directly. Useful for components that fill their given area (e.g., bordered inputs) or that know their height upfront.

Source

pub fn use_desired_height( &mut self, handler: impl Fn(u16, &P, &S) -> Option<u16> + Send + Sync + 'static, )

Declare a dynamic height callback for this component.

The handler receives the available width, the component’s current props, and state, and returns the desired height (or None to fall back to use_height_hint if set, or probe-render measurement otherwise).

This takes priority over use_height_hint since it is width-aware. Use use_height_hint instead when the height is fixed and does not depend on width or state.

Trait Implementations§

Source§

impl<P: Send + Sync + 'static, S: Send + Sync + 'static> Default for Hooks<P, S>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<P, S> !RefUnwindSafe for Hooks<P, S>

§

impl<P, S> !Sync for Hooks<P, S>

§

impl<P, S> !UnwindSafe for Hooks<P, S>

§

impl<P, S> Freeze for Hooks<P, S>

§

impl<P, S> Send for Hooks<P, S>

§

impl<P, S> Unpin for Hooks<P, S>

§

impl<P, S> UnsafeUnpin for Hooks<P, S>

Blanket Implementations§

Source§

impl<T, V> AddTo<DataChildren<T>> for V
where V: Into<T>,

Source§

type Handle<'a> = DataHandle where T: 'a

Handle returned after adding. Supports .key() / .width() chaining.
Source§

fn add_to(self, collector: &mut DataChildren<T>) -> DataHandle

Add this value to the collector, returning a handle for chaining .key() and .width().
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.