Skip to content

Instantly share code, notes, and snippets.

@jhonnymichel
Last active March 27, 2019 01:41
Show Gist options
  • Save jhonnymichel/68de7752b90604b2e3ee04e5911d017e to your computer and use it in GitHub Desktop.
Save jhonnymichel/68de7752b90604b2e3ee04e5911d017e to your computer and use it in GitHub Desktop.
hookstore.js
import { useState } from 'react';
export const store = {
state: {},
setState(value) {
this.state = value;
this.setters.forEach(setter => setter(this.state));
},
setters: []
};
// Bind the setState function to the store object so
// we don't lose context when calling it elsewhere
store.setState = store.setState.bind(store);
// this is the custom hook we'll call on components.
export function useStore() {
const [ state, set ] = useState(store.state);
if (!store.setters.includes(set)) {
store.setters.push(set);
}
return [ state, store.setState ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment