Skip to content

Instantly share code, notes, and snippets.

@intrnl
Last active November 11, 2020 05:47
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 intrnl/9ee75b34a30dbd6cd5ee9d212493d9dc to your computer and use it in GitHub Desktop.
Save intrnl/9ee75b34a30dbd6cd5ee9d212493d9dc to your computer and use it in GitHub Desktop.
import { render } from 'preact';
import { useRef, useState } from 'preact/hooks';
function useReactive (initialState) {
let [, forceUpdate] = useState({});
let reactive = useRef(null);
if (!reactive.current) {
reactive.current = new Proxy(initialState, {
set (target, prop, value, receiver) {
if (target[prop] !== value) {
forceUpdate({});
}
return Reflect.set(target, prop, value, receiver);
},
});
}
return reactive.current;
}
function App() {
let state = useReactive({ count: 0 });
return (
<div>
<p>{Date.now()}</p>
<p>{state.count}</p>
<button onClick={() => state.count++}>+</button>
<button onClick={() => state.count--}>-</button>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment