Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Last active September 23, 2019 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleclarson/3e6575fb225c897bb21ee840b508884a to your computer and use it in GitHub Desktop.
Save aleclarson/3e6575fb225c897bb21ee840b508884a to your computer and use it in GitHub Desktop.
import { createHook } from './createHook'
class App {
count = 0
increaseCount() {
this.count++
}
decreaseCount() {
this.count--
}
}
const useApp = createHook(new App())
function App() {
const app = useApp()
return (
<div className="App">
<h1>{app.count}</h1>
<button onClick={app.decreaseCount}>decrease</button>
<button onClick={app.increaseCount}>increase</button>
</div>
)
}
// TODO: call "ReactDOM.render"
import { useEffect } from 'react'
import { Auto } from '../auto'
import { useConstant, useDispose, useForceUpdate } from './common'
export function createHook<T extends object>(app: T) {
return function useApp() {
const onDirty = useForceUpdate()
const auto = useConstant(() => new Auto({ lazy: true, onDirty }))
useDispose(() => auto.dispose())
useEffect(() => {
if (!auto.commit()) onDirty()
})
return auto.wrap(app, true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment