Function avalanche::hooks::state [−][src]
pub fn state<'a, T: 'static, F: FnOnce() -> T>(
ctx: Context<'a>,
f: F
) -> (Tracked<&'a T>, StateSetter<T>)
Expand description
A hook that allows a component to keep persistent state across renders.
state
takes a type parameter T
specifying the type of the state variable the hook manages, as well as
a parameter F
specifying the type of a function providing a default value for T
.
On first call, the given state will be initialized with f
; it will not be called on subsequent calls of the same
state
call site.
The return value contains a tracked reference to the current state,
and the setter StateSetter. &T
’s lifetime is only valid within the component’s render
function, but StateSetter may be freely moved and cloned.
To update the state, use the set or update methods on the setter variable.
Example
use avalanche::{component, tracked, View, state};
use avalanche_web::components::{Div, H2, Button, Text};
#[component]
fn Counter() -> View {
let (count, set_count) = state(self, || 0);
Div!(
children: [
H2!(
child: Text!("Counter!"),
),
Button!(
on_click: move |_| set_count.update(|count| *count += 1),
child: Text!("+")
),
Text!(tracked!(count))
]
)
}
Adapted from the avalanche_web
counter example.