Skip to content

Instantly share code, notes, and snippets.

@claudiobusatto
Created November 27, 2022 19:51
Show Gist options
  • Save claudiobusatto/536b59e77523183cbdde197b424123c7 to your computer and use it in GitHub Desktop.
Save claudiobusatto/536b59e77523183cbdde197b424123c7 to your computer and use it in GitHub Desktop.
Minimal React example
const React = (() => {
let hooks = [];
let idx = 0;
function useState(initValue) {
let state = hooks[idx] || initValue;
let _idx = idx;
let setState = (newValue) => {
hooks[_idx] = newValue;
};
idx += 1;
return [state, setState];
}
function render(component) {
idx = 0;
const c = component();
c.render();
return c;
}
return { useState, render };
})();
function MyComponent() {
const [count, setCount] = React.useState(1);
const [text, setText] = React.useState("Message");
return {
render: () => console.log({ count, text }),
click: () => setCount(count + 1),
type: () => setText(word),
};
}
let app = React.render(MyComponent); // { count: 1, text: "Message" }
app.click();
app = React.render(MyComponent); // { count: 2, text: "Message" }
app.click();
app = React.render(MyComponent); // { count: 3, text: "Message" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment