use_state

Function use_state 

Source
pub fn use_state<T: 'static>(init: impl FnOnce() -> T) -> State<T>
Expand description

Creates a reactive state value initialized with the returned value of the init callback.

This hook creates a State<T> that is automatically scoped to the current component. The state will be cleaned up when the component unmounts.

§Parameters

  • init: A closure that returns the initial value for the state

§Type Requirements

The type T must be 'static (no borrowed references).

§Example

fn counter() -> impl IntoElement {
    let mut count = use_state(|| 0);

    rect().child(format!("Count: {}", count.read())).child(
        Button::new()
            .child("Increment")
            .on_press(move |_| *count.write() += 1),
    )
}

§Advanced Usage

// Complex initialization
let mut user_data = use_state(|| {
    // Expensive computation or data loading
    String::from("default_preferences")
});

§See Also

  • State for the reactive state type
  • freya-radio crate for global state management