Skip to content

Instantly share code, notes, and snippets.

@intrnl

intrnl/use-reactive.jsx

Last active Nov 11, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.