React:SimpleImplementation
lastmod 2026-11-10created 2022-09-232 edits
이 문서는 React의 핵심 동작을 수십 줄의 JavaScript로 흉내 내어 원리를 이해하기 위한 간단한 구현 예제이다. useState가 상태를 저장하고 변경 시 다시 렌더링을 호출하는 과정, useEffect가 렌더링 뒤에 실행되는 과정, createRoot가 컴포넌트 함수의 반환값을 DOM에 넣는 과정을 최소 형태로 보여 준다. 가상 DOM이나 재조정(reconciliation)은 생략되어 있다.
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);