Skip to content

Instantly share code, notes, and snippets.

@andregardi
Created April 8, 2019 01:22
Show Gist options
  • Select an option

  • Save andregardi/83e03d77fa52dcef33af24f26a127926 to your computer and use it in GitHub Desktop.

Select an option

Save andregardi/83e03d77fa52dcef33af24f26a127926 to your computer and use it in GitHub Desktop.
function setState(newState) {
this.state = { ...this.state, ...newState };
this.listeners.forEach((listener) => {
listener(this.state);
});
}
function useCustom(React) {
const newListener = React.useState()[1];
React.useEffect(() => {
// Called just after component mount
this.listeners.push(newListener);
return () => {
// Called just before the component unmount
this.listeners = this.listeners.filter(listener => listener !== newListener);
};
}, []);
return [this.state, this.setState];
}
const useGlobalHook = (React, initialState) => {
const store = { state: initialState, listeners: [] };
store.setState = setState.bind(store);
return useCustom.bind(store, React);
};
export default useGlobalHook;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment