Skip to content

Instantly share code, notes, and snippets.

@Gerst20051
Last active April 8, 2022 10:38
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 Gerst20051/83ebc3689df7667fbe49a04b9f875b61 to your computer and use it in GitHub Desktop.
Save Gerst20051/83ebc3689df7667fbe49a04b9f875b61 to your computer and use it in GitHub Desktop.
Reacting Nodes
// https://onecompiler.com/javascript/3xyh52rrn
class ReactingNodes {
#nodes = {};
node(component) {
return [this.#nodes[component], component in this.#nodes, this.update(component)];
}
update(component) {
return value => {
if (value === this.#nodes[component]) return;
console.log(`old: ${this.#nodes[component]} - new: ${value}`);
this.#nodes[component] = value;
component();
};
}
useState(component, defaultValue) {
const [value, exists, update] = this.node(component);
return [exists ? value : defaultValue, update];
}
}
const nodes = new ReactingNodes();
function useState(defaultValue) {
return nodes.useState(this, defaultValue);
}
function Component() {
const [time, setTime] = useState.call(Component, Date.now());
console.log(time);
setTimeout(() => {
setTime(Math.random() < .75 ? time : Date.now());
}, 1000);
}
function App() {
return (
Component()
);
}
App();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment