Skip to content

Instantly share code, notes, and snippets.

@35d
Last active February 14, 2019 06:40
Show Gist options
  • Save 35d/5cd8560b6fb6f72d455ed05ccf58860f to your computer and use it in GitHub Desktop.
Save 35d/5cd8560b6fb6f72d455ed05ccf58860f to your computer and use it in GitHub Desktop.
Hooks Test
import React from 'react';
import ReactDOM from 'react-dom';
import { getStateAndActions } from './reducer';
const Button = props => (
<button type="button" onClick={props.onClick}>
{props.children}
</button>
);
const App = () => {
const [state, actions] = getStateAndActions();
return (
<React.Fragment>
{state.test}
<Button onClick={actions.addTest}>Add 1</Button>
<Button onClick={actions.removeTest}>Remove 1</Button>
<Button onClick={actions.reset}>Reset</Button>
</React.Fragment>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
import { useReducer } from 'react';
const initialState = {
count: 0
};
const reducer = (state, action) => {
switch (action.type) {
case 'reset':
return initialState;
case 'addTest':
return { count: state.count + 1 };
case 'removeTest':
return { count: state.count - 1 };
}
};
const mapDispatch = dispatch => ({
reset: () => dispatch({ type: 'reset' }),
addTest: () => dispatch({ type: 'addTest' }),
removeTest: () => dispatch({ type: 'removeTest' })
});
export const getStateAndActions = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const actions = mapDispatch(dispatch);
return [state, actions];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment