Function yew::functional::use_reducer[][src]

pub fn use_reducer<T, F>(initial_fn: F) -> UseReducerHandle<T> where
    T: Reducible + 'static,
    F: FnOnce() -> T, 
Expand description

This hook is an alternative to use_state. It is used to handle component’s state and is used when complex actions needs to be performed on said state.

The state is expected to implement the Reducible trait which provides an Action type and a reducer function.

Example


/// reducer's Action
enum CounterAction {
    Double,
    Square,
}

/// reducer's State
struct CounterState {
    counter: i32,
}

impl Default for CounterState {
    fn default() -> Self {
        Self { counter: 1 }
    }
}

impl Reducible for CounterState {
    /// Reducer Action Type
    type Action = CounterAction;

    /// Reducer Function
    fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
        let next_ctr = match action {
            CounterAction::Double => self.counter * 2,
            CounterAction::Square => self.counter.pow(2)
        };

        Self { counter: next_ctr }.into()
    }
}

#[function_component(UseReducer)]
fn reducer() -> Html {
    // The use_reducer hook takes an initialization function which will be called only once.
    let counter = use_reducer(CounterState::default);

   let double_onclick = {
        let counter = counter.clone();
        Callback::from(move |_| counter.dispatch(CounterAction::Double))
    };
    let square_onclick = {
        let counter = counter.clone();
        Callback::from(move |_| counter.dispatch(CounterAction::Square))
    };

    html! {
        <>
            <div id="result">{ counter.counter }</div>

            <button onclick={double_onclick}>{ "Double" }</button>
            <button onclick={square_onclick}>{ "Square" }</button>
        </>
    }
}