Last active
April 26, 2019 06:59
-
-
Save asbjornh/2cba05a298f317337de5870418683148 to your computer and use it in GitHub Desktop.
useActions: custom React hook
This file contains hidden or 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'; | |
| const useActions = (actions, initialState) => { | |
| const [state, setState] = React.useState(initialState); | |
| const functions = Object.entries(actions).reduce( | |
| (accumulator, [name, action]) => ({ | |
| ...accumulator, | |
| [name]: () => setState(action) | |
| }), | |
| {} | |
| ); | |
| return [state, functions, setState]; | |
| }; | |
| export default useActions; |
This file contains hidden or 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
| // Example usage | |
| const actions = { | |
| add: count => count + 1, | |
| subtract: count => count - 1, | |
| }; | |
| const Counter = () => { | |
| const [count, { add, subtract }, setCount] = useActions(actions, 0); | |
| return ( | |
| <div> | |
| <button onClick={add}> + </button> | |
| <button onClick={subtract}> - </button> | |
| <button onClick={() => setCount(0)}> Reset </button> | |
| {count} | |
| </div> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment