React:SimpleImplementation
react 간단한 구현 방법.
react.js
let value = 0;
let baseElement = null;
let currentComponent = null;
let effectFn = null;
let _renderCount = 0;
const setState = (newValue) => {
value = newValue;
render(currentComponent);
};
const useState = (initValue) => {
return [value || initValue, setState];
};
const useEffect = (cb, dep) => (effectFn = cb);
const render = (component) => {
currentComponent = component;
const html = component();
baseElement.innerHTML = html;
if (_renderCount < 1) effectFn && effectFn();
_renderCount++;
};
const createRoot = (baseEl) => {
baseElement = baseEl;
return { render };
};
export { useEffect, useState, createRoot };
Usage
import { useEffect, useState, createRoot } from "./react.js";
import "./styles.css";
function App() {
const [count, setCount] = useState(0);
window.setCount = setCount;
window.count = count;
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos/10")
.then((response) => response.json())
.then((json) => setCount(count + json.id));
}, []);
return `<div className="App">
<h1>Hello CodeSandbox</h1>
<button className="button-basic"
onClick="setCount(count + 1);">
카운트 증가하기
</button>
<div>count: ${count}</div>
</div>
`;
}
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(App);