-
[React]VanilaJs 로 React Hooks 만들기카테고리 없음 2024. 5. 2. 10:38
- 에러상황
export function createHooks(callback) { let stateContext = {current:0, states:[]}; let memoContext = {current:0, memoValue:{}}; function resetContext() { stateContext.current = 0; memoContext.current = 0; } const useState = (initState) => { const {current, states} = stateContext; const _index = stateContext.current; //초기값 설정 if(states.length === _index){ states.push(initState); } //state할당하기 const state = states[_index]; const setState = (newState) => { //기존의 state와 동일한 경우 if(newState === state) return; states[_index] = newState; callback(); } stateContext.current+=1; return [state, setState]; }; const useMemo = (fn, refs) => { const {current, memoValue} = memoContext; const key = JSON.stringify(refs); if (key in memoValue) { return memoValue[key]; } const result = fn(); memoValue[key] = result; return result; }; return { useState, useMemo, resetContext }; }setState 함수 내에서 상태가 변경되었을 때만 callback 함수가 호출되므로, 상태가 이전과 동일한 경우에는 렌더링이 발생하지 않아야되는데 기존코드는 state에 states[_index]의 값을 할당해줘서 newState === state가 다른주소로 인식되어서 값이 동일해도 주소값이 달라서 렌더링이 계속 발생되었음
const useState = (initState) => { const {current, states} = stateContext; stateContext.current+=1; //초기값 설정 if(states.length === current){ states.push(initState); } let state = states[current] const setState = (newState) => { //기존의 state와 동일한 경우 if(newState === states[current]) return; states[current] = newState; callback(); } return [state, setState]; };