Skip to main content

Hooks

Struct Hooks 

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

Effect collector for declarative lifecycle management.

Components receive a Hooks instance in their lifecycle method and use it to declare effects. The framework calls lifecycle after every build and update, clearing old effects and applying the new set — so effects are always consistent with current props and state.

§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

fn lifecycle(&self, hooks: &mut Hooks<TimerState>, state: &TimerState) {
    if self.running {
        hooks.use_interval(Duration::from_secs(1), |s| s.elapsed += 1);
    }
    hooks.use_mount(|s| s.started_at = Instant::now());
    hooks.use_unmount(|s| println!("ran for {:?}", s.started_at.elapsed()));
}

Implementations§

Source§

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

Source

pub fn use_interval( &mut self, interval: Duration, handler: impl Fn(&mut 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 &mut State and any mutations automatically mark the component dirty.

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

Examples found in repository?
examples/chat.rs (lines 215-217)
214    fn lifecycle(&self, hooks: &mut Hooks<StreamingDotsState>, _state: &StreamingDotsState) {
215        hooks.use_interval(Duration::from_millis(300), |s| {
216            s.frame = s.frame.wrapping_add(1);
217        });
218    }
Source

pub fn use_mount(&mut self, handler: impl Fn(&mut 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).

Examples found in repository?
examples/lifecycle.rs (lines 81-88)
78    fn lifecycle(&self, hooks: &mut Hooks<StatusLogState>, _state: &StatusLogState) {
79        if !self.name.is_empty() {
80            let mount_name = self.name.clone();
81            hooks.use_mount(move |state| {
82                state.log(
83                    format!("  {} mounted", mount_name),
84                    Style::default()
85                        .fg(Color::Green)
86                        .add_modifier(Modifier::ITALIC),
87                );
88            });
89
90            let unmount_name = self.name.clone();
91            hooks.use_unmount(move |state| {
92                state.log(
93                    format!("  {} unmounted", unmount_name),
94                    Style::default()
95                        .fg(Color::Red)
96                        .add_modifier(Modifier::ITALIC),
97                );
98            });
99        }
100    }
Source

pub fn use_unmount(&mut self, handler: impl Fn(&mut 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.

Examples found in repository?
examples/lifecycle.rs (lines 91-98)
78    fn lifecycle(&self, hooks: &mut Hooks<StatusLogState>, _state: &StatusLogState) {
79        if !self.name.is_empty() {
80            let mount_name = self.name.clone();
81            hooks.use_mount(move |state| {
82                state.log(
83                    format!("  {} mounted", mount_name),
84                    Style::default()
85                        .fg(Color::Green)
86                        .add_modifier(Modifier::ITALIC),
87                );
88            });
89
90            let unmount_name = self.name.clone();
91            hooks.use_unmount(move |state| {
92                state.log(
93                    format!("  {} unmounted", unmount_name),
94                    Style::default()
95                        .fg(Color::Red)
96                        .add_modifier(Modifier::ITALIC),
97                );
98            });
99        }
100    }
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.

Examples found in repository?
examples/chat.rs (line 84)
83    fn lifecycle(&self, hooks: &mut Hooks<Self::State>, _state: &Self::State) {
84        hooks.use_autofocus();
85    }
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
fn lifecycle(&self, hooks: &mut Hooks<MyState>, _state: &MyState) {
    hooks.provide_context(self.event_sender.clone());
}
Source

pub fn use_context<T: Any + Send + Sync + 'static>( &mut self, handler: impl FnOnce(Option<&T>, &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) 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’s lifecycle method returns.

§Example
fn lifecycle(&self, hooks: &mut Hooks<MyState>, _state: &MyState) {
    hooks.use_context::<Sender<AppEvent>>(|sender, state| {
        state.tx = sender.cloned();
    });
}

Auto Trait Implementations§

§

impl<S> Freeze for Hooks<S>

§

impl<S> !RefUnwindSafe for Hooks<S>

§

impl<S> Send for Hooks<S>
where S: Send,

§

impl<S> !Sync for Hooks<S>

§

impl<S> Unpin for Hooks<S>
where S: Unpin,

§

impl<S> UnsafeUnpin for Hooks<S>

§

impl<S> !UnwindSafe for Hooks<S>

Blanket Implementations§

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.