Created
April 8, 2019 01:22
-
-
Save andregardi/83e03d77fa52dcef33af24f26a127926 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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