Skip to content

Instantly share code, notes, and snippets.

@seriousManual
Last active April 17, 2020 08:34
Show Gist options
  • Save seriousManual/675b3e4de70f1858e4983c96c138b233 to your computer and use it in GitHub Desktop.
Save seriousManual/675b3e4de70f1858e4983c96c138b233 to your computer and use it in GitHub Desktop.
simple add-hoc react state managment
import { Emitter } from 'events'
import React from 'react'
function createInstance() {
const globalAppState = {
foo: 'bar',
spam: 'eggs'
}
function render() {
ReactDOM.render(<App {...globalAppState}/>, document.getElementById('root'));
};
const emitter = new Emitter();
emitter
.on('update-foo', (newFoo) => {
globalAppState.foo = newFoo;
render();
})
.on('update-spam', async () => {
const newSpam = await fetch('/spam');
globalAppState.spam = newSpam;
render();
});
const EmitterContext = React.createContext(emitter);
function App(foo, spam) {
return (
<EmitterContext.Provider value={emitter}>
<div>
<h1>ohay, {foo}!</h1>
Today on the menu: {spam}
<UpdatePlz />
</div>
</EmitterContext.Provider>
)
}
function UpdatePlz() {
const emitter = useContext(EmitterContext);
return (
<div>
<button onClick={() => emitter.emit('update-foo', Math.random())}>set foo to random</button>
<button onClick={() => emitter.emit('update-spam')}>new spam plz!!!</button>
</div>
)
}
}
createInstance()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment