Created
November 27, 2022 19:51
-
-
Save claudiobusatto/536b59e77523183cbdde197b424123c7 to your computer and use it in GitHub Desktop.
Minimal React example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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