자 이제 hook 뉴비에게는 끝판왕이라 할 수 있는 useEffect를 만들어보자.
먼저, 만들어보기 전에 useEffect()는 이렇다.
useEffect(() => {
console.log('마운트 될 때만 실행됩니다.');
}, []);
이렇게 생겼다. useEffect는 첫 번째 인자로 콜백함수를 두 번째 인자로 배열을 넘겨주는 것 같다. 이제 추가해보자.
const React = (function(){
let hooks = [];
let idx = 0;
function useState(initVal){
const _idx = idx;
const state = hooks[idx] || initVal;
const setState = newVal => {
hooks[_idx] = newVal;
};
idx++;
return [state,setState];
}
function useEffect(callBack,dependecyArray) {
const oldDepenpendcy = hooks[idx];
let hasChanged = true;
if (oldDepenpendcy){
hasChanged = dependecyArray.some(
(dependency, index) => !Object.is(dependency, oldDepenpendcy[index])
);
}
if(hasChanged) callBack();
hooks[idx] = dependecyArray;
idx ++;
}
function render(Component){
idx = 0;
const C = Component();
C.render();
return C;
}
return { useState, useEffect, render };
})();
function Component() {
const [count,setCount] = React.useState(1);
const [text, setText] = React.useState('apple');
React.useEffect(() => {
console.log('유즈이펙트다!')
},[])
return {
render: () => console.log(count, text),
click: () => setCount(count+1),
type: word => setText(word),
};
}
var App = React.render(Component);
App.click();
var App = React.render(Component);
App.type('peer');
var App = React.render(Component);
우선은 이렇게 만들 수 있다.
자 이제 전체 코드를 보면 복잡하니 useEffect 관련 코드만 뜯어보자.
const React = (function(){
//...생략
function useEffect(callBack,dependecyArray) {
const oldDepenpendcy = hooks[idx];
let hasChanged = true;
if (oldDepenpendcy){
hasChanged = dependecyArray.some(
(dependency, index) => !Object.is(dependency, oldDepenpendcy[index])
);
}
if(hasChanged) callBack();
hooks[idx] = dependecyArray;
idx ++;
}
//...생략
})();
function Component() {
//...생략
React.useEffect(() => {
console.log('유즈이펙트다!')
},[])
//...생략
}
hook 기초 박살내기 끝.