Skip to content

Instantly share code, notes, and snippets.

@asbjornh
Last active April 26, 2019 06:59
Show Gist options
  • Select an option

  • Save asbjornh/2cba05a298f317337de5870418683148 to your computer and use it in GitHub Desktop.

Select an option

Save asbjornh/2cba05a298f317337de5870418683148 to your computer and use it in GitHub Desktop.
useActions: custom React hook
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;
// 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