Last active
March 27, 2019 01:41
-
-
Save jhonnymichel/68de7752b90604b2e3ee04e5911d017e to your computer and use it in GitHub Desktop.
hookstore.js
This file contains 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 { 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