개요
이번 시간에는 render.ts에 이벤트 리스닝 로직을 추가하고 버튼을 클릭했을 시에 이벤트 발생
useState로 리렌더링까지 구현해보겠다
이벤트 판별 로직 작성
// 이벤트 판별
if (key.startsWith("on") && typeof value === "function") {
const eventType = key.slice(2).toLowerCase();
domElement.addEventListener(eventType, value);
continue;
}
render.ts에 해당 함수를 추가하여 props에 event가 있을 시 setAttribute 하는 것이 아닌 addEventListner로 이벤트 핸들링을 해주겠다
main.ts
const dom = document.querySelector("#app");
if (dom) {
const button = createElement(
"button",
{
onClick: () => alert("버튼 클릭!"),
id: "my-button",
style: {
backgroundColor: "blue",
color: "white",
padding: "10px 20px",
border: "none",
borderRadius: "10px",
cursor: "pointer",
marginTop: "10px",
},
},
"클릭",
);
const div = createElement(
"div",
{ id: "greeting" },
createElement("h1", null, "Hello, Mini React!"),
createElement("p", null, "직접 만든 렌더러 입니다."),
button,
);
render(div, dom as HTMLElement);
}
간단한 스타일링 후 버튼을 렌더링 해준다


버튼 클릭 이벤트가 작동하는 것을 확인할 수 있다.
useState 로직
use-state.ts
const states: unknown[] = [];
let hookIndex = 0;
export function useState<T>(initialValue: T): [T, (newValue: T) => void] {
const currentIndex = hookIndex;
// hookIndex를 증가시켜 다음 useState 호출 시 다른 인덱스를 사용하도록 함
hookIndex++;
// states 배열에 현재 인덱스에 해당하는 값이 없으면 초기값을 설정
if (states[currentIndex] === undefined) {
states[currentIndex] = initialValue;
}
const state = states[currentIndex] as T;
const setState = (newValue: T) => {
states[currentIndex] = newValue;
};
return [state, setState];
}
해당 로직 작성 후

화면에서 버튼을 하염없이 클릭 해보았지만 값과 화면은 변하지 않았다.
이유는
- 상태만 바뀌고 화면을 다시 그리지 않음
- 클릭할 때마다 같은 값 저장
- 재실행 전에 hookIndex를 초기화 해줘야함
수정본
const states: unknown[] = [];
let hookIndex = 0;
export function registerRerenderCallback(callback: () => void) {
// 상태가 변경될 때마다 호출되는 콜백을 등록하는 로직을 구현할 수 있습니다.
// 예를 들어, 상태 변경 시 UI를 다시 렌더링하도록 설정할 수 있습니다.
// 이 예제에서는 간단히 콘솔에 메시지를 출력하도록 합니다.
callback();
}
export function resetHookIndex() {
hookIndex = 0;
}
export function useState<T>(initialValue: T): [T, (newValue: T) => void] {
const currentIndex = hookIndex++;
// 현재 인덱스에 해당하는 상태가 존재하지 않으면 초기값으로 설정
if (!(currentIndex in states)) {
states[currentIndex] = initialValue;
}
const state = states[currentIndex] as T;
const setState = (newValue: T) => {
states[currentIndex] = newValue;
};
return [state, setState];
}
main.ts
const dom = document.querySelector("#app");
if (dom) {
registerRerenderCallback(rerender);
rerender();
}
function rerender() {
resetHookIndex();
dom?.replaceChildren();
const counterElement = Counter();
render(counterElement, dom as HTMLElement);
}
function Counter() {
const [counter, setCounter] = useState(0);
const CounterButton = createElement(
"button",
{
id: "my-button",
style: {
backgroundColor: "blue",
color: "white",
padding: "10px 20px",
border: "none",
borderRadius: "10px",
cursor: "pointer",
marginTop: "10px",
},
onClick: () => {
setCounter(counter + 1);
rerender();
},
},
"클릭",
);
const CounterDisplay = createElement(
"p",
{ id: "counter-display", style: { marginTop: "10px" } },
`카운터 값: ${counter}`,
);
return createElement(
"div",
{ id: "greeting" },
createElement("h1", null, "Hello, Mini React!"),
createElement("p", null, "직접 만든 렌더러 입니다."),
CounterDisplay,
CounterButton,
);
}
스코프 밖에서 Counter 컴포넌트와 rerender 함수를 정의하여 버튼 클릭 후 setCounter 작동 시에 리렌더링이 작동하도록 로직을 작성하였다

카운터가 제대로 작동한 것을 볼 수 있다
하지만 현재는 useState함수가 다중 컴포넌트를 지원하지 않는다.
다중 컴포넌트 지원하기
use-state.ts
let currentComponentInstance: ComponentInstance | null = null;
// functional component를 호출할 때마다 새로운 ComponentInstance를 생성하고,
// 해당 인스턴스를 currentComponentInstance에 설정합니다.
// 그리고 functional component의 렌더링이 끝나면 이전 인스턴스로 되돌립니다.
export function withComponentInstance<T>(
instance: ComponentInstance,
callback: () => T,
): T {
const previous = currentComponentInstance;
currentComponentInstance = instance;
instance.hookIndex = 0;
try {
return callback();
} finally {
currentComponentInstance = previous;
}
}
withComponentInstance 함수를 선언하여 함수형 컴포넌트 마운트 시에 인스턴스를 초기화 하도록 작성한다
그 후에
render.ts > render()
if (element.type instanceof Function) {
const Component = element.type;
// ComponentInstance를 관리하기 위해 전달받은 키를 사용
const instanceKey = element.props._componentInstanceKey;
if (instanceKey === undefined) {
throw new Error("함수 컴포넌트에 _componentInstanceKey를 전달해야 합니다.");
}
// instanceMap에서 ComponentInstance 가져오기, 없으면 새로 생성
let instance = instanceMap.get(instanceKey);
if (!instance) {
instance = { states: [], hookIndex: 0 };
instanceMap.set(instanceKey, instance);
}
const child = withComponentInstance(instance, () =>
Component(element.props),
);
render(child, container);
return;
}
그 후 Functional component 일 때 instance를 map으로 저장해서 각각의 컴포넌트에서 다른 state를 사용할 수 있도록 작성해준다.
main.ts > rerender()
export function rerender() {
dom?.replaceChildren();
const counterElement = createElement(Counter, {
_componentInstanceKey: "counter-1",
});
const counterElement2 = createElement(Counter, {
_componentInstanceKey: "counter-2",
});
render(counterElement, dom as HTMLElement);
render(counterElement2, dom as HTMLElement);
}
main.ts의 rerender함수에서 Counter 컴포넌트를 두 개 렌더링하고

확인 결과 서로 다른 컴포넌트에서 각각의 state 값을 가진 것을 확인할 수 있다.