Created
May 2, 2021 03:55
-
-
Save ccorcos/21f50bae3553de1212fbfa9ebeaf1dcc 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
// This object encapsulates the state and dispatches events. | |
class Store<T> { | |
constructor(public state: T) {} | |
public setState = (nextState: T) => { | |
this.state = nextState | |
this.emit() | |
} | |
private listeners = new Set<(state: T) => void>() | |
public addListener(fn: (state: T) => void) { | |
this.listeners.add(fn) | |
return () => this.listeners.delete(fn) | |
} | |
private emit() { | |
this.listeners.forEach(fn => fn(this.state)) | |
} | |
} | |
// Hook that subscribes to a store. | |
function useStore<T>(store: Store<T>) { | |
const [state, setState] = useState(store.state) | |
useEffect(() => { | |
return store.addListener(setState) | |
}, [store]) | |
return [state, store.setState] as const | |
} | |
// Initialize the global state here, wire up into context or pass through props | |
// but notice that the store reference never changes, so the props/context don't change either. | |
function App() { | |
const store = useMemo(() => new Store(0), []) | |
return ( | |
<div> | |
<Slider store={store}/> | |
<Value store={store}/> | |
</div> | |
) | |
} | |
// Subscribe to the store inside. | |
function Slider({store}) { | |
const [value, setValue] = useStore(store) | |
return <input type="range" value={value} onChange={e => setValue(e.target.value)}/> | |
} | |
function Value({store}) { | |
const [value] = useStore(store) | |
return <div>{value}</div> | |
} |
Author
ccorcos
commented
May 2, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment