UseReducer<T> constructor
UseReducer<T> (
- Reducer<
T> reducer, - T initialState
A ReactterHook that manages state using reducer method.
UseReducer accepts a reducer method and returns the current state paired with a dispatch method. (If you’re familiar with Redux, you already know how this works.)
Contains a value of type T
which represents the current state.
When value is different to previous state,
UseReducer execute update to notify to container instance
that has changed and in turn executes onWillUpdate
and onDidUpdate
.
Example:
class Store {
final int count;
Store({this.count = 0});
}
Store _reducer(Store state, ReactterAction<String, int?> action) {
switch (action.type) {
case 'increment':
return Store(count: state.count + (action.payload ?? 1));
case 'decrement':
return Store(count: state.count + (action.payload ?? 1));
default:
throw UnimplementedError();
}
}
class AppController {
late final state = UseReducer(_reducer, Store(count: 0));
AppController() {
print("count: ${state.value.count}"); // count: 0;
state.dispatch(ReactterAction(type: 'increment', payload: 2));
print("count: ${state.value.count}"); // count: 2;
state.dispatch(ReactterAction(type: 'decrement'));
print("count: ${state.value.count}"); // count: 1;
}
}
Implementation
UseReducer(
this.reducer,
T initialState,
) : _state = UseState<T>(initialState) {
UseEffect(update, [_state]);
}