useReducer<TState, TAction, TInit> function

ReducerHook<TState, TAction, TInit> useReducer<TState, TAction, TInit>(
  1. TState reducer(
    1. TState state,
    2. TAction action
    ),
  2. TState initialState
)

Initializes state of a DartFunctionComponent to initialState and creates a dispatch method.

Example:

Map reducer(Map state, Map action) {
  switch (action['type']) {
    case 'increment':
      return {...state, 'count': state['count'] + 1};
    case 'decrement':
      return {...state, 'count': state['count'] - 1};
    default:
      return state;
  }
}

UseReducerTestComponent(Map props) {
  final state = useReducer(reducer, {'count': 0});

  return react.Fragment({}, [
    state.state['count'],
    react.button({
      'onClick': (_) => state.dispatch({'type': 'increment'})
    }, [
      '+'
    ]),
    react.button({
      'onClick': (_) => state.dispatch({'type': 'decrement'})
    }, [
      '-'
    ]),
  ]);
}

Learn more: reactjs.org/docs/hooks-reference.html#usereducer.

Implementation

ReducerHook<TState, TAction, TInit> useReducer<TState, TAction, TInit>(
    TState Function(TState state, TAction action) reducer, TState initialState) {
  final result = React.useReducer(allowInterop(reducer), initialState);
  return ReducerHook._(result[0] as TState, result[1] as void Function(TAction));
}