Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useStore #37

Open
thchia opened this issue Oct 27, 2018 · 3 comments
Open

useStore #37

thchia opened this issue Oct 27, 2018 · 3 comments

Comments

@thchia
Copy link

thchia commented Oct 27, 2018

Using useReducer to create a global state object, store in Context and accessed with useContext:

const MyContext = createContext();

function MyProvider(props) {
  let [state, dispatch] = useGlobalState();

  return (
    <MyContext.Provider value={{ state, dispatch }}>
      {props.children}
    </MyContext.Provider>
  );
}

export function useMyContext() {
  return useContext(MyContext);
}

function MyConsumer() {
  let { state, dispatch } = useMyContext()

  return (
    <button onClick={() => dispatch({ type: 'SOME_THING' })}>
      {state.some.thing}
    </button>
  )
}

https://gist.github.com/thchia/dd1bc8200fd8cff89cfa6c928983e5c4

@giuseppeg
Copy link

cc @philipp-spiess

@philipp-spiess
Copy link

Check out https://github.com/philipp-spiess/use-store. It's not using useReducer to set up the store (maybe we can manage to add support for that?) but you can use your existing Redux-like store with ease and interact with the store outside of React as well.

@thchia
Copy link
Author

thchia commented Oct 27, 2018

@philipp-spiess looks great! I was coming at it more from the perspective of a non-redux user, and thinking about it in super simple terms. i.e. combining useContext and useReducer to offer a way to store and update a complex, app-global object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants