Last active
February 14, 2019 06:40
-
-
Save 35d/5cd8560b6fb6f72d455ed05ccf58860f to your computer and use it in GitHub Desktop.
Hooks Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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