Function intuitive::state::use_state

source ·
pub fn use_state<T, F>(initializer: F) -> State<T>where
    T: 'static + Send,
    F: FnOnce() -> T,
Expand description

A hook for managing state within a Component

Similarly to React Hooks, use_state lets you manager state without an explicit struct storing state. use_state returns a State, which can be used to retrieve or update the value. For example,

#[component(Input)]
fn render(title: String) {
  let text = use_state(|| String::new());

  let on_key = on_key! { [text]
    KeyEvent { code: Char(c), .. } => text.mutate(|text| text.push(c)),
    KeyEvent { code: Backspace, .. } => text.mutate(|text| text.pop()),
  };

  render! {
    Section(title) {
      Text(text: text.get(), on_key)
    }
  }
}

Gotchas

Any calls to use_state must always be called in the same order and in every render. This means that there can not be any conditional logic around the calling of use_state. If Intuitive detects such a violation, it will panic with an appropriate message.