Skip to content

A governor hook to manage state with actions for, and by, the people.

License

Notifications You must be signed in to change notification settings

msmith-techempower/react-governor

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

92 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React Governor

NPM VERSION PRs Welcome Open Issues Build Status

Use a governor hook to manage state with actions for, and created by, the people.

Available as an npm package.

What is useGovernor?

useGovernor is a hook which can be used in any functional component, just like useReducer, but unlike useReducer there is no need for the developer to build the boilerplate of actions, dispatch, and reducer.

Let's See it in Action

const initialState = { count: 1 };

const contract = {
  increment() {
    return state => ({
      count: state.count + 1
    });
  },
  add(val) {
    return state => ({
      count: state.count + val
    });
  }
}

export default function Counter() {

  const [state, actions] = useGovernor(initialState, contract);

  return (
    <div>
      <span>Current Count: {state.count}</span>
      <button onClick={() => actions.increment()}>Increment</button>
      <button onClick={() => actions.add(5)}>Add 5</button>
    </div>
  );
}

Test that this works

This should feel very similar to how useReducer works with actions and reducers.

useGovernor expects a collection of actions to act as the contract. These actions are functions which take in any number of arguments and the current state. These actions are responsible for returning an object that describes what in the state should be mutated.

As from our example, the increment action returns a reducer function describing that the state should be mutated such that count is this.state.count + 1. Similarly, the add action returns an object describing that the state should be mutated such that count is this.state.count + val, and notice that when we called add that we passed it a value to add.

About

A governor hook to manage state with actions for, and by, the people.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%