Skip to content

Instantly share code, notes, and snippets.

@rainerborene
Last active March 21, 2019 19:20
Show Gist options
  • Save rainerborene/eeb9ee9ecea36f92bb3c61b2791eb455 to your computer and use it in GitHub Desktop.
Save rainerborene/eeb9ee9ecea36f92bb3c61b2791eb455 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react'
const store = {
state: {},
setters: []
};
export function setStore(value) {
store.state = value;
store.setters.forEach(setter => setter(store.state));
}
export function useStore() {
const [ state, set ] = useState(store.state);
if (!store.setters.includes(set)) {
store.setters.push(set);
}
useEffect(() => () => {
store.setters = store.setters.filter(setter => setter !== set)
}, [])
return [ state, setStore ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment