useReducerLazy<TState, TAction, TInit> function

ReducerHook<TState, TAction, TInit> useReducerLazy<TState, TAction, TInit>(
  1. TState reducer(
    1. TState state,
    2. TAction action
    ),
  2. TInit initialArg,
  3. TState init(
    1. TInit
    )
)

Initializes state of a DartFunctionComponent to init(initialArg) and creates dispatch method.

Example:

Map initializeCount(int initialValue) {
  return {'count': initialValue};
}

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};
    case 'reset':
      return initializeCount(action['payload']);
    default:
      return state;
  }
}

UseReducerTestComponent(Map props) {
  final ReducerHook<Map, Map, int> state = useReducerLazy(reducer, props['initialCount'], initializeCount);

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

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

Implementation

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