pub fn create_reducer<'a, U, Msg>(
    cx: Scope<'a>,
    initial: U,
    reduce: impl Fn(&U, Msg) -> U + 'a
) -> (&'a ReadSignal<U>, impl Fn(Msg) + 'a)
Expand description

An alternative to create_signal that uses a reducer to get the next value.

It uses a reducer function that takes the previous value and a message and returns the next value.

Returns a ReadSignal and a dispatch function to send messages to the reducer.

Params

  • initial - The initial value of the state.
  • reducer - A function that takes the previous value and a message and returns the next value.

Example

enum Msg {
    Increment,
    Decrement,
}

let (state, dispatch) = create_reducer(cx, 0, |state, msg: Msg| match msg {
    Msg::Increment => *state + 1,
    Msg::Decrement => *state - 1,
});

assert_eq!(*state.get(), 0);
dispatch(Msg::Increment);
assert_eq!(*state.get(), 1);
dispatch(Msg::Decrement);
assert_eq!(*state.get(), 0);