Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 58 additions & 1 deletion example/test/function_component_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,55 @@ HookTestComponent(Map props) {
]);
}

var useReducerTestFunctionComponent =
react.registerFunctionComponent(UseReducerTestComponent, displayName: 'useReducerTest');

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({
'key': 'urt1',
'onClick': (_) => state.dispatch({'type': 'increment'})
}, [
'+'
]),
react.button({
'key': 'urt2',
'onClick': (_) => state.dispatch({'type': 'decrement'})
}, [
'-'
]),
react.button({
'key': 'urt3',
'onClick': (_) => state.dispatch({
'type': 'reset',
'payload': props['initialCount'],
})
}, [
'reset'
]),
]);
}

var useCallbackTestFunctionComponent =
react.registerFunctionComponent(UseCallbackTestComponent, displayName: 'useCallbackTest');

Expand Down Expand Up @@ -128,18 +177,26 @@ void main() {
hookTestFunctionComponent({
'key': 'useStateTest',
}, []),
react.br({'key': 'br'}),
react.br({'key': 'br1'}),
react.h2({'key': 'useCallbackTestLabel'}, ['useCallback Hook Test']),
useCallbackTestFunctionComponent({
'key': 'useCallbackTest',
}, []),
react.br({'key': 'br2'}),
react.h2({'key': 'useContextTestLabel'}, ['useContext Hook Test']),
newContextProviderComponent({
'key': 'provider'
}, [
useContextTestFunctionComponent({
'key': 'useContextTest',
}, []),
]),
react.br({'key': 'br3'}),
react.h2({'key': 'useReducerTestLabel'}, ['useReducer Hook Test']),
useReducerTestFunctionComponent({
'key': 'useReducerTest',
'initialCount': 10,
}, []),
]),
querySelector('#content'));
}
Expand Down
141 changes: 141 additions & 0 deletions lib/hooks.dart
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,147 @@ void useEffect(dynamic Function() sideEffect, [List<Object> dependencies]) {
}
}

/// The return value of [useReducer].
///
/// The current state is available via [state] and action dispatcher is available via [dispatch].
///
/// > __Note:__ there are two [rules for using Hooks](https://reactjs.org/docs/hooks-rules.html):
/// >
/// > * Only call Hooks at the top level.
/// > * Only call Hooks from inside a [DartFunctionComponent].
///
/// Learn more: <https://reactjs.org/docs/hooks-reference.html#usereducer>.
class ReducerHook<TState, TAction, TInit> {
/// The first item of the pair returned by [React.userReducer].
TState _state;

/// The second item in the pair returned by [React.userReducer].
void Function(TAction) _dispatch;

ReducerHook(TState Function(TState state, TAction action) reducer, TState initialState) {
final result = React.useReducer(allowInterop(reducer), initialState);
_state = result[0];
_dispatch = result[1];
}

/// Constructor for [useReducerLazy], calls lazy version of [React.useReducer] to
/// initialize [_state] to the return value of [init(initialArg)].
///
/// See: <https://reactjs.org/docs/hooks-reference.html#lazy-initialization>.
ReducerHook.lazy(
TState Function(TState state, TAction action) reducer, TInit initialArg, TState Function(TInit) init) {
final result = React.useReducer(allowInterop(reducer), initialArg, allowInterop(init));
_state = result[0];
_dispatch = result[1];
}

/// The current state map of the component.
///
/// See: <https://reactjs.org/docs/hooks-reference.html#usereducer>.
TState get state => _state;

/// Dispatches [action] and triggers stage changes.
///
/// > __Note:__ The dispatch function identity is stable and will not change on re-renders.
///
/// See: <https://reactjs.org/docs/hooks-reference.html#usereducer>.
void dispatch(TAction action) => _dispatch(action);
}

/// Initializes state of a [DartFunctionComponent] to [initialState] and creates [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'],
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#nit having state.state is a little confusing; I wonder if we could come up with a different name for the hook return value...

store? 😄 🤷‍♂ Nah, that's probably not better...

/// react.button({
/// 'onClick': (_) => state.dispatch({'type': 'increment'})
/// }, [
/// '+'
/// ]),
/// react.button({
/// 'onClick': (_) => state.dispatch({'type': 'decrement'})
/// }, [
/// '-'
/// ]),
/// ]);
/// }
/// ```
///
/// Learn more: <https://reactjs.org/docs/hooks-reference.html#usereducer>.
ReducerHook<TState, TAction, TInit> useReducer<TState, TAction, TInit>(
TState Function(TState state, TAction action) reducer, TState initialState) =>
ReducerHook(reducer, initialState);

/// 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: <https://reactjs.org/docs/hooks-reference.html#lazy-initialization>.
ReducerHook<TState, TAction, TInit> useReducerLazy<TState, TAction, TInit>(
TState Function(TState state, TAction action) reducer, TInit initialArg, TState Function(TInit) init) =>
ReducerHook.lazy(reducer, initialArg, init);

/// Returns a memoized version of [callback] that only changes if one of the [dependencies] has changed.
///
/// > __Note:__ there are two [rules for using Hooks](https://reactjs.org/docs/hooks-rules.html):
Expand Down
1 change: 1 addition & 0 deletions lib/react_client/react_interop.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ abstract class React {

external static List<dynamic> useState(dynamic value);
external static void useEffect(dynamic Function() sideEffect, [List<Object> dependencies]);
external static List<dynamic> useReducer(Function reducer, dynamic initialState, [Function init]);
external static Function useCallback(Function callback, List dependencies);
external static ReactContext useContext(ReactContext context);
}
Expand Down
Loading